简体   繁体   中英

ForEach returns empty array - Node.js

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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