如果可以
.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())
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)