首页 > 解决方案 > 我可以在 forEach() 数组助手之后链接一个 .then() 吗?

问题描述

我可以做这样的事情吗?

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

array.forEach(item => process(item)).then(() => {
    //run after forEach is done processing the whole array
});

标签: javascriptasynchronousforeachcallback

解决方案


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

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


推荐阅读