简体   繁体   English

如何在Node.js中获取async.each的结果

[英]How to get the result of async.each in Node.js

I'm trying to fill outputArray and then send it as a JSON. 我正在尝试填充outputArray,然后将其作为JSON发送。 When I add console.log() after outputArray.push I can see that outputArray is being filled. 当我在outputArray.push之后添加console.log() ,我可以看到outputArray正在被填充。 But in the bottom function, it prints an empty array. 但是在底部函数中,它会打印一个空数组。 I see that the bottom function works before the array is filled. 我看到底部函数在数组被填充之前起作用。 How can I modify below code so that I can receive the full array. 如何修改下面的代码,以便可以接收完整的数组。 Thanks in advance. 提前致谢。

      var outputArray = [];

      async.each(generalArr, function(item, callback)
      {
          var docs =  collection.find({ id: { "$in": item}}).toArray();


        docs.then(function(singleDoc)
        {
          if(singleDoc)
          {


              outputArray.push.apply(outputArray, singleDoc);
          }
        });
        callback(null, outputArray);

    }, function(err,results)
      {
      if (err) 
        return console.log('ERROR', err);

      console.log(results);
      res.json(results);


      }
  ) 

There are a couple of mistakes in the code. 代码中有两个错误。

  1. You are calling callback(null, outputArray) in the wrong place. 您在错误的地方调用了callback(null, outputArray) It should be right after the innermost if condition 它应该是最里面之后if条件
  2. async.each final callback takes only one argument - err , so results is not available async.each最后的回调仅接受一个参数err ,因此results不可用

The following code should work... 下面的代码应该工作...

var outputArray = [];

async.each(generalArr, function(item, callback) {
    var docs =  collection.find({ id: { "$in": item}}).toArray();
    docs.then(function(singleDoc) {
        if(singleDoc) {
            outputArray.push.apply(outputArray, singleDoc);
        }
        callback();
    });
}, function(err) {
    if (err) return console.log('ERROR', err);

    console.log(outputArray);
    res.json(outputArray);
});

I'm assuming that catch code is also there for the DB promise query, else the final callback might never be called. 我假设DB Promise查询也有catch代码,否则最终的回调可能永远不会被调用。

Don't use async.js when plain promises are so much easier: 当简单的承诺要容易得多时,请不要使用async.js:

Promise.all(generalArr.map(function(item) {
  return collection.find({id: {"$in": item}}).toArray();
})).then(function(outputArray) {
  var results = outputArray.filter(Boolean);
  console.log(results);
  res.json(results);
}, function(err) {
  console.log('ERROR', err);
});

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

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