如何顺序执行promise,从数组中传递参数?

如何顺序执行promise,从数组中传递参数?,第1张

如何顺序执行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())


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5148802.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存