首页 > 解决方案 > 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 ,这似乎是一个很好的实现。

标签: javascriptnode.jsasynchronouspromisepromise.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);
        
}

推荐阅读