我可以在 forEach() 数组助手之后链接一个 .then() 吗?



我可以做这样的事情吗?

const array = ["foo", "bar", "hello", "etc"];
array.forEach(item => process(item)).then(() => {
    //run after forEach is done processing the whole array
});

No. 则用于处理承诺。forEach 是同步的,因此您可能应该将处理的项目保存在新数组中,然后立即执行后处理逻辑。

const values = ["foo", "bar", "hello", "etc"];
Promise.all(values.map(process)).then((results)=>{
    //run after all promises are resolved
    console.log(results instanceof Array); // prints true
});

您可以使用 Promise.all() 解析 promise 数组,并使用 values.map(process) 作为参数为每个数组项执行 process() 函数。

如果你打算在forEach之后执行一些步骤,那么你可以通过顺序步骤来实现它,因为(forEach是同步的)

执行行 1

const array = ["foo", "bar", "hello", "etc"];

执行线 2

array.forEach(item => process(item))

执行行 3

//Write your steps here to do after array.forEach

最新更新