You can use a recursive callback handler that knows when to stop based on a base case, in the below code it executes once for each item in arr. Also you can use async.series() which is a pre-made library to handle this.
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)
If you want to use Promises, bluebird has mapSeries() which will serially iterate over a collection with the given async function.
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))
If MethodwithCallback() can be promisified, then we can shorten this code a little. Promisification is now built into Node as well via util.promisify()
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)
})
Methodwithcallbackasynchronous ?