javascript - Async / Await 与 Promise 语法
问题描述
我试图让一个 for 循环等到它解决。
这是我所在的地方,但它不起作用......
function myotherfunction() {
// do something
console.log("myotherfunction");
}
async function myfunction() {
var arr = ['one', 'two', 'three'];
for (let i = 0; i < arr.length; i++) {
await new Promise(resolve => {
myotherfunction();
console.log('done');
});
}
}
myfunction()
如何修复我的语法?
解决方案
重构您的代码,使myotherfunction
函数返回一个承诺,以便您可以在循环内等待它。
myotherfunction() {
return new Promise((resolve, reject) => {
// Resolve on some condition
return resolve();
});
}
async myfunction() {
var arr = ['one', 'two', 'three'];
for (let i = 0; i < arr.length; i++) {
await myotherfunction();
}
}
推荐阅读
- windows - 使用带有文件夹名称模式的 cmd compact
- angular - 如何在父组件之后初始化子组件?
- android - Flutter 调用 setState() 来更新另一个类中的 UI
- python - 向 RESNET50 添加层以构建 JOIN CNN 模型
- c# - 这个迭代列表的powershell脚本有什么问题?Foreach-Object -Process { Set-Alias ... }
- git - 私有存储库的私有分支
- jquery - JQuery:如何从 div 中提取 li 项目
- python-3.x - 使用python分别提取图像中的每一行
- python - 源文件中带有 Wsgi 模块的 Apache 不会立即受到影响
- sql - SQL:如何从长 xml 字符串中提取我想要的子字符串?