首页 > 解决方案 > 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()

如何修复我的语法?

标签: javascript

解决方案


重构您的代码,使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();
  }
}

推荐阅读