javascript - promises.push() 立即运行,不等待 promises.all()
问题描述
我有一个 nodejs 函数processReviews(workflow)
,当被调用时,它应该将多个承诺推送到一个数组,然后在 for 循环promises[]
之后运行它们。promises.all()
function examplePromiseFunc(){
return new Promise((resolve, reject) => {
console.log("examplePromiseFunc() INSIDE ")
resolve('done')
})
}
async function processReviews(workflow){
//get objects from s3
let allObjects = await getAllObjects(workflow);
allObjects = allObjects.filter(obj => obj.Key.includes('output.json'))
console.log(`found ${allObjects.length} .json files.`)
const promises = [];
for (let i = 0; i < allObjects.length; i++) {
console.log('i=',i,' pushing to promises[]')
promises.push( examplePromiseFunc() )
}
const result = await Promise.all(promises)
console.log('running, result = ', result);
}
但是当我运行我的代码时,输出如下所示:
found 697 .json files.
i= 0 pushing to promises[]
examplePromiseFunc() INSIDE
i= 1 pushing to promises[]
examplePromiseFunc() INSIDE
i= 2 pushing to promises[]
examplePromiseFunc() INSIDE
i= 3 pushing to promises[]
examplePromiseFunc() INSIDE
...
这意味着每次我向我的 promises[] 数组 ( promises.push( await examplePromiseFunc() )
) 推送一个 promise 时,该函数examplePromiseFunc()
都会立即被调用并且不会等待。
我希望我的函数只在我await Promise.all(promises)
最后运行时被调用,有什么我遗漏的吗?我的异步函数会导致问题吗?我一直在阅读 javascript promises.all ,这似乎是一个很好的实现。
解决方案
问题是您已经await
在循环内部使用,这意味着循环将“等待”并按顺序处理项目。
相反,您应该只将承诺添加到数组中,然后await
像您一样在最后添加所有承诺:
async function processReviews(workflow) {
//get objects from s3
const allObjects = await getAllObjects(workflow);
const promises = [];
for (let i = 0; i < allObjects.length; i++) {
// Don't await the promise here, just start it and add it to the array.
promises.push(examplePromiseFunc(allObjects[i]));
}
const result = await Promise.all(promises)
console.log(result);
}
推荐阅读
- c++ - 树结构中的运行时元素替换
- c - 如何在编译器上获得不同的结果?
- java - 尝试执行后期服务时出现 ResourceAccessException
- python - 在 Python 中使用 Selenium 单击网页中的所有按钮
- java - 无法使用 Heroku postgres 将数据添加到 Spring Boot 上的数据库
- sql - 在asp中插入点分隔值而不是逗号
- express - multer上传多个文件
- azure-devops - 是否有可能一次实现一整套潜在依赖的工件(微服务)?
- typescript - 你如何声明一个值约束类型?
- pyspark - 使用 pyspark 将数据从 kafka 写入 hive - 卡住