等待嵌套的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(...)
。
等待嵌套的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(...)
。