1

I am learning Node.js; due to asynchronous of Node.js I am facing an issue:

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?

And this code is asynchronous, is it possible if we make a complete function synchronous?

4
  • What do you mean result is null? It should at least be an empty array. Commented Jun 22, 2015 at 20:21
  • ohh my fault it is an empty array , but for loop its length is 2 , but inside domain.Cameras.count() callback its value is empty array Commented Jun 22, 2015 at 20:47
  • If result is null, there should most probably be an error. You don't seem to be checking the error object here. Commented Jun 23, 2015 at 5:48
  • @ZeMoon The result is not null , it is an empty array Commented Jun 23, 2015 at 6:21

2 Answers 2

2

@jmingov is right. 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.

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

        });
Sign up to request clarification or add additional context in comments.

6 Comments

can you please check , I got every time value of i=3 , inside cameraCountFunctions.push() . I think this is due to loop is fully executed first and value of i set to 3
I'm sorry, I don't understand. Is there an error raised when i = 3?
Yes actually result is an array of 3 element , and when it try to do domain.Cameras.count({"userId": result[i].id} so value of i=3 so result[3] is null , so it is trying to get from null this is an error
If result is an array of three elements, then the loop should not even reach i = 3.
@abhaygarg12493 I have edited my answer. please check the same
|
0

Try to do async programing allways when doing node.js, this is a must. Or youll end with big performance problems.

Check this module: https://github.com/caolan/async it can help.

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

1 Comment

No , I want to use resullt of domain.User.find() inside domain.Cameras.count() callback

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.