zpjrra
Last Updated: September 19, 2016
·
22.75K
· riyadhalnur
10309058 10152457564452360 4465802230248535815 n

Async Waterfall in Nodejs

The async library for Node and client side is a pretty nifty library which takes out some of the pain of doing things asynchronously. This example is for the server side using Node.

According to the repo, this is what the waterfall does - "Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error."

var create = function (req, res) {
    async.waterfall([
        _function1(req),
        _function2,
        _function3
    ], function (error, success) {
        if (error) { alert('Something is wrong!'); }
        return alert('Done!');
    });
};

function _function1 (req) {
    return function (callback) {
        var something = req.body;
        callback (null, something);
   }
}

function _function2 (something, callback) {
    return function (callback) {
       var somethingelse = function () { // do something here };
       callback (err, somethingelse);
    }
}

function _function3 (something, callback) {
    return function (callback) {
      var somethingmore = function () { // do something here };
      callback (err, somethingmore);
    }
}