Mayukh Roy
Mayukh Roy

Reputation: 1815

async.applyEachSeries couldnot refer to 'this' unlike async.series

Is there any alternative of async.applyEachSeries?

Here is a piece of code which fails to refer to this when used with applyEachSeries. But, works as usual for async.series.

this.c is the place where I am focusing on:

var LModel = function(){};
LModel.prototype = {

    a: function (req, done) {
        console.log(' FUNCTION A');
        done(null,'result A');
    },
    b: function (req, done) {
        console.log('THIS==', this.c); //THIS== undefined for applyEachSeries
        console.log(' FUNCTION B');
        this.c(req, function(err, res){console.log('c CALLED!'); console.log(res);});

        done(null,'result B');
    },
    c: function (req, callback) {
        console.log(' FUNCTION C');
        callback(null,'result C');
    }
};

module.exports = LModel;


var lanM = new LModel();

async.applyEachSeries([lanM.a, lanM.b],{},function(err, res){console.log('NEVER EXECUTED!');})

async.series([
        function(callback){
            // do some stuff ...
            lanM.a({}, function(err, res){});

            callback(null, 'one');
        },
        function(callback){
            // do some more stuff ...
            lanM.b({}, function(err, res){});
            callback(null, 'two');
        }
    ],
    // optional callback
    function(err, results){
        // results is now equal to ['one', 'two']
    });

Upvotes: 0

Views: 58

Answers (1)

Niklas Ingholt
Niklas Ingholt

Reputation: 477

You can make it work by using bind on your lanM.b method like this:

async.applyEachSeries([lanM.a, lanM.b.bind(lanM)], {}, 
  function(err, res) {
    console.log('NEVER EXECUTED!');
})

Upvotes: 1

Related Questions