Say I have an array and a function A:
var array = ['a', 'b', 'c'];
function A(p) { ... };
now I want to pass each item of array to function A, and want them to be executed in a sequential order. usually there won't be any problem. I can do:
array.forEach(function(item) {
A(item);
}
however, if there are some asynchronous action in A, everything becomes messed up. so the question is:
How can I have them executed orderly even if there are asynchronous actions in A?
By which I mean, I want A('b') to be executed after A('a') is completely finished (including all the asynchronous actions in there).
I guess there must have been some utilities doing such things already. can someone shed me some light?
This is a perfect use case for "eachSeries" from async.js
You could use it this way
async.eachSeries(array, A, function(err) {
// this function gets called at the end
// after your array has been looped
});
And you would have to modify your A function with a second parameter - a callback.
function A(p, callback) {
// ...
return callback();
}
That calls the callback parameter once your async calls in A are finished.
JavaScript Promises allow you to do just that.
This example is pretty convoluted, but it shows some aspects of using Promises:
var arr = ['a', 'b', 'c'];
function processAsync(val) {
return new Promise(function(res, rej) {
console.log("Starting:", val);
setTimeout(function () {
console.log("Done:", val);
res();
}, 1000);
});
}
arr.reduce(function(promise, i) {
return promise.then(processAsync.bind(null, i));
}, Promise.resolve());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With