1

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){
    ???
}
2
  • 1
    Commonly known as callback hell... Commented Dec 27, 2013 at 2:32
  • 1
    Take a look at async library Commented Dec 27, 2013 at 2:34

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.