承诺中的承诺队列

时间:2019-10-28 17:36:11

标签: javascript

then的情况下,我处于某个Promise中,那里有一些数组,我需要调用异步函数队列,并将数组的下100个项目作为参数(长度未知)。

uri = [{id: 1}, {id: 2}, ...];

somePromiseFunction()
  .then((resp) => function2(resp.id, uri));

function2一次可以获取100个项目,完成后可能需要再获取100个项目。

2 个答案:

答案 0 :(得分:0)

从这样零碎的信息很难说,但是...

如果要并行调用它们...

...使用mapPromise.all

.then(() => Promise.all(theArray.slice(0, 100).map(item => theAsyncFunction(item))))

请注意,如果结束索引超出数组的末尾,slice可以接受。

如果theAsyncFunction仅使用其第一个参数,而忽略了您传递的任何其他参数,则可以直接将其传递给map而不是使用箭头函数:

.then(() => Promise.all(theArray.slice(0, 100).map(theAsyncFunction)))

如果要同时删除来自数组的条目,则可以使用splice代替slice

.then(() => Promise.all(theArray.splice(0, 100).map(theAsyncFunction)))

splice将删除原始数组中的条目(对其进行修改)并返回这些条目的数组。

如果要连续运行它们...

...使用“承诺减少技巧”:

.then(() =>
    theArray.slice(0, 100).reduce((p, item) =>
        p.then(() => theAsyncFunction(item)),
        Promise.resolve()
    )
)

...如果要删除它们,请再次使用splice

答案 1 :(得分:0)

了解如何使用async/await。它应该简化您的代码执行。

`let asyncFuntion = async function(data){
// do stuff
}

let sampleArray = []  // assume it has 100 elements
let execArray = []

 for(let elem of sampleArray){
    execArray.push(asyncFuntion(elem))
 }

 let resultArray = await Promise.all(execArray) // it would executed all  the 100 elements in async way

 // you have all 100 element's results in this resultArray`