迭代时使Node.js代码在Mongoose中同步

时间:2015-06-22 20:18:33

标签: node.js mongoose

我正在学习Node.js;由于Node.js的异步,我遇到了一个问题:

domain.User.find({userName: new RegExp(findtext, 'i')}).sort('-created').skip(skip).limit(limit)
        .exec(function(err, result) {

                for(var i=0;i<result.length;i++){
                    console.log("result is ",result[i].id);
                    var camera=null;
                    domain.Cameras.count({"userId": result[i].id}, function (err, cameraCount) {
                        if(result.length-1==i){
                            configurationHolder.ResponseUtil.responseHandler(res, result, "User List ", false, 200);
                        }
                    })
                }
            })

我想在Cameras回调中使用结果,但这里是空数组,所以无论如何都要得到它?

这段代码是异步的,如果我们使一个完整的函数同步,它是否可能?

2 个答案:

答案 0 :(得分:2)

@jmingov是对的。您应该使用async module执行parallel requests来获取User.find查询中返回的每个用户的计数。

以下是演示流程:

var Async = require('async'); //At the top of your js file.

domain.User.find({userName: new RegExp(findtext, 'i')}).sort('-created').skip(skip).limit(limit)
        .exec(function(err, result) {

            var cameraCountFunctions = [];

            result.forEach(function(user) {

               if (user && user.id)
               {
                    console.log("result is ", user.id);
                    var camera=null; //What is this for?

                    cameraCountFunctions.push( function(callback) {

                        domain.Cameras.count({"userId": user.id}, function (err, cameraCount) {

                                if (err) return callback(err);

                                callback(null, cameraCount); 
                        });
                    });
               }
            })

            Async.parallel(cameraCountFunctions, function (err, cameraCounts) {
                    console.log(err, cameraCounts);
                    //CameraCounts is an array with the counts for each user.
                    //Evaluate and return the results here.
            }); 

        });

答案 1 :(得分:0)

尝试在执行node.js时始终执行异步编程,这是必须的。或者你最终会遇到很大的性能问题。

检查此模块:https://github.com/caolan/async它可以提供帮助。

以下是代码中的问题:

domain.Cameras.count({
    "userId": result[i].id
}, function(err, cameraCount) {

    // the fn() used in the callback has 'cameraCount' as argument so
    // mongoose will store the results there.

    if (cameraCount.length - 1 == i) { // here is the problem
        //  result isnt there it should be named 'cameraCount'   
        configurationHolder.ResponseUtil.responseHandler(res, cameraCount, "User List ", false, 200);
    }
});