简体   繁体   English

ForEach返回空数组-Node.js

[英]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. res.json(arr)响应空数组。 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. 您的问题是,即使getAllCustomers尚未完成,您的callback也会被调用。 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 您应该在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
        });
      });

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

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