javascript - 我可以在 forEach() 数组助手之后链接一个 .then() 吗?
问题描述
我可以做这样的事情吗?
const array = ["foo", "bar", "hello", "etc"];
array.forEach(item => process(item)).then(() => {
//run after forEach is done processing the whole array
});
解决方案
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()
每个数组项的函数作为参数。
推荐阅读
- algorithm - 如何计算生产中现有代码的时间复杂度
- minikube - 为什么 YugaByteDB YSQL 选择查询在使用 bytea 数据类型时会返回意外字节?
- r - R中的复杂(ish)pivot_longer
- css - ionic admob 横幅广告关闭选项卡菜单
- mongodb - 无法在 openshift 中部署 mongodb 社区运营商
- flutter - 页面授权令牌
- c++ - 可以为 64 位目标使用 GCC“--enable-frame-pointer”
- reactjs - Gridjs-react:按具有 React 组件的列排序
- swift - 我怎么能在初始化期间失败?
- javascript - 如何在 GET 响应中显示数组中的特定元素