等待嵌套的 forEach 行为

Mon*_*aya 5 javascript node.js

为什么这个片段

const firstArray = ['toto', 'toto'];
const secondArray = ['titi', 'titi'];
firstArray.forEach(async (toto, i) =>
{
  await secondArray.forEach(async titi =>
  {
    // async code
    console.log(titi, i);
  });
  // async code
  console.log(toto, i);
});
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

输出

删除await关键字会产生预期的输出

在此输入图像描述

我的猜测是它存在于await关键字的行为中,因为没有它,生成的输出就是预期的输出。

编辑:这纯粹是一个微不足道的问题。我想了解为什么在 forEach 之前使用 wait 提供这种行为。这背后没有“具体代码”。

EDIT2:编辑了片段,因为评论和答案反映了对我的问题的误解

ask*_*ndz 5

forEach 同步工作,这意味着它不会对每次迭代的返回(在本例中为承诺)执行任何操作,并且会忽略它。

如果您使用:

for(let item of arrayItems)
Run Code Online (Sandbox Code Playgroud)

或者一个普通的 for 循环,您应该看到异步工作的预期结果。


sp0*_*00m 0

我猜你想在继续之前等待所有承诺。Array.prototype.reduce(...)如果是这种情况,和Array.prototype.map(...)的组合Promise.all(...)将更适合:

const allPromises = firstArray.reduce((accumulatedPromises, toto) => {
  const secondArrayPromises = secondArray.map((titi) => {
    return // some promise;
  });
  const firstArrayPromise = // some promise;
  return accumulatedPromises.concat(secondArrayPromises, firstArrayPromise);
}, []);
const finalPromise = Promise.all(allPromises);
Run Code Online (Sandbox Code Playgroud)

然后,await finalPromise如果您在 内async function,或者使用.then(...).