async.mapSeries with a nested callback function and variable scope

626 Views Asked by At

My problem is with variable scope, async.mapSeries and nested call back functions. I need to iterate a collection and call a stored procedure based on a values in the collection.

So far my code is as follows

var _var1 = "";

LoadData(sp, callback)
{
    //mysql stuff
    connection.connect();

    var query = connection.query(sp, function(err, rows, fields){
        if (err) console.log(err);
        connection.end();
        callback(rows[0]);
    });
}

otherfunction() {

    //retdata returned from another function 

    async.mapSeries(retdata,function(rd, rdCb){

        LoadData(options, function (row) {
            var _content = new Buffer(row[0].content, 'base64').toString('ascii');
            //can't get _content to the callback, and _var1 isn't in scope here       
        });
        //next     
        rdCb();
    },function(err,results){
        //need _content accessible here to iterate through data 
    });

any ideas folks?

1

There are 1 best solutions below

3
On BEST ANSWER

You're calling the callback synchronously, which defeats the point of using the async module. You should pass the data to the callback:

async.mapSeries(retdata,function(rd, rdCb){
    LoadData(options, function (row) {
        var _content = new Buffer(row[0].content, 'base64').toString('ascii');
        rdCb(null, _content);
    });
},function(err,results){
    //_results is now what you expect
});