0

I am using node async feature. I am forming new array by iterating the existing array. I would like to return the new array after the call back is finished. res.json(arr) responds empty array. Help me identifying the problem.

 getAllUsers(function(users) {
       var arr = [];
        async.forEach(users, function(user, callback) {
          var id = user._id;
          getAllCustomers(id, function(customers) {
            var count = customers.length;
            user.customers = count;
            arr.push(user);
          });
          callback();

        }, function(err) {
          console.log('iterating done');
          res.json(arr); // returns [], empty array
        });
      });
1
  • 1
    How are you calling this function Commented Jul 12, 2017 at 5:56

2 Answers 2

1

Your problem is, even if the getAllCustomers is not finished your callback is called. Please try the following:

getAllUsers(function(users) {
   var arr = [];
    async.each(users, function(user, callback) {
      var id = user._id;
      getAllCustomers(id, function(customers) {
        var count = customers.length;
        user.customers = count;
        arr.push(user);
        callback();
      });


    }, function(err) {
      console.log('iterating done');
      res.json(arr); // returns [], empty array
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

1

you should use callback inside getAllCustomers

getAllUsers(function(users) {
       var arr = [];
        async.forEach(users, function(user, callback) {
          var id = user._id;
          getAllCustomers(id, function(customers) {
            var count = customers.length;
            user.customers = count;
            arr.push(user);
          callback();

          });


        }, function(err) {
          console.log('iterating done');
          res.json(arr); // returns [], empty array
        });
      });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.