最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

等待嵌套的forEach行为

运维笔记admin9浏览0评论

等待嵌套的forEach行为

等待嵌套的forEach行为

为什么这个片段

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);
});

产生以下输出:

卸下await关键字产生预期的输出

我的猜测是它驻留在await关键字的行为,因为,没有它,则产生的输出是预期的输出。

编辑:这是一个纯粹的琐碎问题。我想知道为什么使用的await一个foreach提供这种行为之前。有没有“具体的代码”这背后。

EDIT2:编辑片段作为意见,回答反映了我的问题的误解

回答如下:

我猜你想继续之前等待所有的承诺。如果应该的话,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);

于是,无论是await finalPromise如果你是一个async function内,或使用.then(...)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论