Doing Something After Asynchronous Calls in Node
Problem
Suppose I have four distinct asynchronous operations that need to be run, and they can all be run independently. But there's one remaining Function that needs to use all the data those Asynchronous Calls collect, so it can only be done once all of them are finished.
A simple way to do this is to make the asynchronous calls call each other one right after the other, and then finally call the final function, like so:
myObj.async1(function () {
myObj.async2(function () {
myObj.async3(function () {
myObj.async4(function () {
...
finalFunction();
But this is a poor way to do it, since node is built around asynchronous functionality for a reason. So instead, let's say we want to do:
myObj.async1(async1Callback);
myObj.async2(async2Callback);
myObj.async3(async3Callback);
myObj.async4(async4Callback);
if( //Some logic here to determine when all four functions have completed
finalFunction();
What's the best way to determine that logic? I considered having each function set a boolean variable to indicate whether it has completed, and then having a time-based emitter that constantly checks if all four variables are set to true and then calls finalFunction if they are, but that can get messy with having all those variables lying around.
Any thoughts on what's the best way to do this?
Solution
I would make use of the async
library for this, e.g.
async.parallel([
myObj.async1,
myObj.async2,
myObj.async3,
myObj.async4
], function(err) {
if (err) throw err;
// Run final function now that all prerequisites are finished
finalFunction();
});
This assumes that each myObj.async*
function
takes a callback function
as its only parameter and that callback's first parameter is an err
param. For more info see the docs for async#parallel()
.
Discussion
View additional discussion.