Reputation: 7782
What I'm doing atm:
function1(function(){
function2(function(){
function3(function(){
function4();
}
}
}
Is there an easier way to do it?
miracleFunction([function1,function2,function3,function4]);
miracleFunction = function(array){
???
}
Upvotes: 1
Views: 93
Reputation: 1611
Instead of going deep into callbacks, break them up into easily understandable functions:
function GetUserData(id, callback) {
// db queries, etc
connection.query('...get user info...', function (err, results) {
connection.query('...get user related whatnot...', function (err, results) {
callback ();
});
});
}
connection.query('...load page data...', function (err, results) {
GetUserData( function () {
res.render('page.ejs', ... );
});
});
You could even break the more used functions off into a module so you don't have too much clutter in your code. The async package looks nice, but to me, personally, I like to see the flow. Always up to programmer's preference.
Upvotes: 0
Reputation: 1960
Take a look at promises which also allow you to handle errors very nicely.
Q is especially nice, and support just your use case. Direct link here: https://github.com/kriskowal/q#sequences
Upvotes: 0
Reputation: 129139
Using the async
package on npm
, you can use an array like that, e.g.:
var async = require('async');
async.series([function1, function2, function3, function4]);
In addition to simply running several asynchronous functions in a series, it also has functions simplifying running asynchronous operations in parallel, mapping an array using an asynchronous function, and various other helpful combinators.
Upvotes: 3