如何顺序执行promise,从数组中传递参数?
var myArray = [1, 2, 3, 4, 5, 6]function myPromise(num){
return new Promise(res => {
window.setTimeout(()=>{
res( console.log("done: " + num) )
},2000)
})
}
myPromise(myArray[0])
.then(x => myPromise(myArray[1]))
.then(x => myPromise(myArray[2]))
.then(x => myPromise(myArray[3]))
.then(x => myPromise(myArray[4]))
.then(x => myPromise(myArray[5]))
现在,如果我执行上面的语句,它将按顺序运行。在我的实际用例中,数组是动态填充的,我需要myPromise()
为中的每个成员执行函数myArray
。
我如何制作一个“暂停循环”,该循环将为数组中的每个项目循环,执行myPromise
并等待promise被解决,然后再继续下一次迭代?
回答:
如果可以.then
按问题中的情况创建与数组元素一样多的Promise,则可以整齐地重复应用fold。
myArray.reduce( (p, x) =>
p.then(_ => myPromise(x)),
Promise.resolve()
)
但是,例如,异步函数不需要:
const mapSeries = async (iterable, action) => { for (const x of iterable) {
await action(x)
}
}
mapSeries(myArray, myPromise)
内置在优秀承诺库Bluebird中的格式为mapSeries
:
Promise.mapSeries(myArray, myPromise)
可运行的代码段:
const myArray = [1, 2, 3, 4, 5, 6]const sleep = ms =>
new Promise(res => {
setTimeout(res, ms)
})
const myPromise = num =>
sleep(500).then(() => {
console.log('done: ' + num)
})
myArray.reduce(
(p, x) =>
p.then(_ => myPromise(x)),
Promise.resolve()
)
以上是 如何顺序执行promise,从数组中传递参数? 的全部内容, 来源链接: utcz.com/qa/430303.html