Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is callback hell?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 307
    Comment on it

    Callback hell is the nesting of callbacks that is one callback inside another. Callback hell is very bad thing in nodejs, you should always avoid it.

     

    To avoid callback hell you can:

    1) Break callback into individual function

    2) User promises

    3) async module of node

     

    I am focusing on only the third method:

     

    async module in node.js

    Series in node js

    It runs an array of functions in series, each on running once the previous function has completed.

    var async =  require('async');
    
    var getUsers = function(callback) {
        callback(null, "one");
    };
    
    var getStats = function(callback) {
        callback(null, "two");
    };
    
    async.series([
        getUsers,
        getStats
    ], function(err, results) {
        console.log(results); //print: ["one", "two"]
    });

    waterfall in nodejs

    It is a series of functions, in which the output of one function acts as the input for the next one,

    var async =  require('async');
    
    var getUsers = function(callback) {
        callback(null, "one");
    };
    
    var getStats = function(arg1, callback) {
        callback(null, arg1);
    };
    
    async.waterfall([
        getUsers,
        getStats
    ], function(err, results) {
        console.log(results); //print: "one"
    });


    parallel in nodejs

    All functions are executed parallely.
     

    var async =  require('async');
    
    var getUsers = function(callback) {
        callback(null, "one");
    };
    
    var getStats = function(arg1, callback) {
        callback(null, "done");
    };
    
    async.parallel([
        getUsers,
        getStats
    ], function(err, results) {
        console.log(results); //print: "one"
    });

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: