您可以使用递归回调处理程序,该处理程序根据基本情况知道何时停止,在下面的代码中,它为arr 中的每个项目执行一次。你也可以使用async.series() 这是一个预制库来处理这个问题。
const arr = [...items]
let count = 0
const blockingHandler = () => {
// Keep track of times invoked
count++
// Do something
// If there is another item to execute, then do it
if (count < arr.length) {
MethodwithCallback(blockingHandler))
}
}
MethodwithCallback(blockingHandler)
如果你想使用 Promises,bluebird 有 mapSeries(),它将使用给定的异步函数串行迭代集合。
const Promise = require('bluebird')
const arr = [...items]
Promise.mapSeries(arr, i => {
MethodwithCallback(() => {
/*
* If there was some error handling you could check for an error
* if there is one, then return a rejected Promise
* if (err) {
* return Promise.reject(err)
* }
*/
// do something
return Promise.resolve()
})
})
.then(() => console.log('All Promises Complete'))
.catch(err => console.log('An error occurred', err))
如果MethodwithCallback() 可以是promisified,那么我们可以稍微缩短这段代码。 Promisification 现在也通过 util.promisify() 内置到 Node 中
const Promise = require('bluebird')
const asyncMethod = Promise.promisify(MethodwithCallback)
const arr = [...items]
Promise.mapSeries(arr, i => {
return asyncMethod()
.then(() => {
// do something specific for this item
})
})
.then(() => {
// do something when all items done
})
.catch(err => {
// An error occurred during mapSeries
console.log('An error occurred', err)
})