简体   繁体   English

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

[英]Make Node.js code synchronous in Mongoose while iterating

I am learning Node.js; 我正在学习Node.js; due to asynchronous of Node.js I am facing an issue: 由于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);
                        }
                    })
                }
            })

I want to use result in Cameras callback but it is empty array here, so is there anyway to get it? 我想在Cameras回调中使用result,但此处为空数组,因此无论如何要获取它?

And this code is asynchronous, is it possible if we make a complete function synchronous? 而且此代码是异步的,如果我们使一个完整的函数同步,是否有可能?

@jmingov is right. @jmingov是正确的。 You should make use of the async module to execute parallel requests to get the counts for each user returned in the User.find query. 您应该使用异步模块执行并行请求,以获取User.find查询中返回的每个用户的计数。

Here's a flow for demonstration: 这是演示流程:

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

        });

Try to do async programing allways when doing node.js, this is a must. 尝试在执行node.js时始终进行异步编程,这是必须的。 Or youll end with big performance problems. 否则您将遇到严重的性能问题。

Check this module: https://github.com/caolan/async it can help. 检查此模块: https : //github.com/caolan/async它可以提供帮助。

Here is the trouble in your code: 这是您的代码中的问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM