在then
的情况下,我处于某个Promise中,那里有一些数组,我需要调用异步函数队列,并将数组的下100个项目作为参数(长度未知)。
uri = [{id: 1}, {id: 2}, ...];
somePromiseFunction()
.then((resp) => function2(resp.id, uri));
function2一次可以获取100个项目,完成后可能需要再获取100个项目。
答案 0 :(得分:0)
从这样零碎的信息很难说,但是...
...使用map
和Promise.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`