具有嵌套回调函数和变量作用域的async.mapSeries

时间:2014-12-15 21:21:51

标签: node.js node-async

我的问题是变量范围,async.mapSeries和嵌套回调函数。我需要迭代一个集合并根据集合中的值调用存储过程。

到目前为止,我的代码如下

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 
    });

任何想法的人?

1 个答案:

答案 0 :(得分:1)

您正在同步调用回调,这违背了使用async模块的要点。您应该将数据传递给回调:

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
});