node.js - Nodejs MongoDb 异步回调

标签 node.js mongodb async.js

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

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

    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

});

最佳答案

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

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

关于node.js - Nodejs MongoDb 异步回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094564/

相关文章:

node.js - 如何在 Node-JS 中创建 Web 服务

node.js - Nodejs MongoDB 具有异步功能更新文档

node.js - 如何将 Node.js 中到达速度过快的事件输入一一写入数据库

javascript - 如何按条件查询具有最新日期的子文档

javascript - 异步函数在调用一次时有效,但多次调用时无效

node.js - 异步 : Combining two mongodb collection using Async. forEach

javascript - 使更新 API 动态化

mongodb - 为什么 mongo db serverStatus connections current 不等于 netstat count

mongodb - 按键查询多级MongoDB对象

javascript - 在 Meteor 1.3+ 中使用异步