Nodejs MongoDb异步回调

时间:2018-01-04 11:44:13

标签: node.js mongodb async.js

我刚开始使用NodeJs并处理异步函数。 我尝试从for循环中执行多个MongoDB调用,我需要等待所有这些调用在下一步之前完成。

我曾尝试使用async实现它,但似乎所有调用之外的变量都无法访问。知道如何让它发挥作用吗?

    var sample = req.body;  // sample will be an array list of items
    var stringList = "";

    var calls = [];
    for(var i = 0; i < sample.length; i++) {
console.log(sample[].item) // i can print it here
        calls.push(function(callback) {
            db3.table.find({column1:sample[i].item}, function(err, temp){  // i hit an error here, it cannot find sample[i].item...
                if (err)
                    return callback(err);
                stringList = stringList + temp[0].item2;
                callback(null, stringList );
            });
        });
    }

    async.parallel(calls, function(err, result) {
        if (err)
            return console.log(err);

console.log(result); // I am expecting a string of all the item2 returned and concatenated previously

});

3 个答案:

答案 0 :(得分:0)

异步并行回调无论如何将数据发送到最终回调,您可以使用此功能合并所有发送的值。

var sample     = req.body;  // sample will be an array list of items
var stringList = "";
var calls      = [];
for (var i = 0; i < sample.length; i++) {
    console.log(sample[i].item) // i can print it here
    calls.push(function (callback) {
        db3.table.find({column1: sample[i].item}, function (err, temp) {
            // i hit an error here, it cannot find sample[i].item...
            if (err) {
                return callback(err);
            }
            callback(null, temp[0].item2);
        });
    });
}

async.parallel(calls, function (err, result) {
    if (err) {
        return console.log(err);
    }
    stringList = result.join('');
    console.log(stringList); // I am expecting a string of all the item2 returned and concatenated previously
});

答案 1 :(得分:0)

也许您可以检查所有数据库查询何时完成:

var sample = req.body;  // sample will be an array list of items
var stringList = "";
var counter = 0;
for(var i = 0; i < sample.length; i++) {
    console.log(sample[].item) // i can print it here
        db3.table.find({column1:sample[i].item}, function(err, temp){  // i hit an error here, it cannot find sample[i].item...
            if (err)
                throw err;
            stringList = stringList + temp[0].item2;
            if(++counter >= sample.length) {
                // when here you will have the whole string
                console.log(stringList); 
            }
        });
    });
}

答案 2 :(得分:0)

每个异步操作都可以表示回调或承诺。这里有两个例子可能会有所帮助

//  sequential execution P.S. use for dependent tasks  
var operations= [1,2,3];
(function loop(index){
    if(index==operations.length) return ;
    setTimeout(function() {
        console.log(`hello ${operations[index]}`);
        loop(++index);
    }, 1000);
})(0)

//  parallel execution P.S. use when independent tasks  
Promise.all(operations.map(val=>{
    return new Promise((resolve, reject) => {
        console.log(`hello ${val}`);
    });
}))
.then(data=>{

})
.catch(err=>{
    console.log(err);
})

了解更多https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise