Javascript 异步等待代码的运行方式与forEach不同

Javascript 异步等待代码的运行方式与forEach不同,javascript,node.js,typescript,async-await,Javascript,Node.js,Typescript,Async Await,我有这段代码,当我运行时,它将按顺序运行'1'和'2' 因此,下面的代码运行良好 (async () => { await runit('one').then(res => { console.info(res); }); await runit('two').then(res => { console.info(res); }); })(); 现在,我想做同样的事情,但在一个循环中,所以我做了如下: const arr = ['one'

我有这段代码,当我运行时,它将按顺序运行'1'和'2'

因此,下面的代码运行良好

(async () => {

  await runit('one').then(res => {
    console.info(res);
  });

  await runit('two').then(res => {
    console.info(res);
  });

})();
现在,我想做同样的事情,但在一个循环中,所以我做了如下:

const arr = ['one', 'two'];
  arr.forEach(element => {
    (async () => {
      await runit(element).then(res => {
      console.info(res);
    });
  })();
});
虽然看起来是相同的代码,但它不再按照顶部代码的顺序运行


如何解决这个问题?

您可以使用
promise实现相同的功能。所有
功能如下

const arr = ['one', 'two'];
const promises = [];
  arr.forEach(element => {
      promises.push(runit(element));
  });

Promise.all(promises).then(results => {
    console.log(results)//you will get results here.
});

它不会等待,因为您执行的函数是异步的,您实际上是在告诉它不要等待。要解决此问题,您可以对cycle执行以下简单操作:

for (let i = 0; i < arr.length; i++) {
  const item = arr[i];
  await runit(item).then(res => {
    console.info(res);
  });
}

后者是首选。

使用
wait
避免
forEach
。它不会正常工作

forEach
忽略它所使用的回调函数的所有结果。如果向其传递一个
async
函数或任何其他返回承诺的函数,则返回的所有承诺都将不被处理

使用本机for循环。 要匹配一次只运行一项的非循环代码,请执行以下操作:

for (const element of ['one', 'two']) {
  console.log(await runit(element));
}
这与其他带有
Promise.all
的答案大不相同<代码>承诺。所有
都等待多个承诺的全面完成,这意味着事情已经并行运行

要并行运行,请执行以下操作:

for (const res of await Promise.all(['one', 'two'].map(runit)) {
  console.log(res);
}

您的第一个示例更像(以简化的方式):
runit('one')。然后(()=>runit('two))
这里有一个使用基本
for
循环的解决方案:虽然在某些情况下很好,但这并不能保证承诺将按时间顺序解决(第一个解决,然后第二个…
runit()
显然会返回一个
承诺
。将此承诺传递给
promise.resolve()
的原因是什么?它将解析与数组索引完全相同的顺序。我的意思是,解析值将在相同的承诺索引上接收。@Andreas收集承诺。因此,我们可以使用
promise.all()
@Andreas()一次性解决所有承诺是的,promise.resolve是完全冗余的。后者并行运行,而前者不并行。
for (const res of await Promise.all(['one', 'two'].map(runit)) {
  console.log(res);
}