简体   繁体   中英

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

I'm trying to fill outputArray and then send it as a JSON. When I add console.log() after outputArray.push I can see that outputArray is being filled. 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. It should be right after the innermost if condition
  2. async.each final callback takes only one argument - err , so results is not available

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.

Don't use async.js when plain promises are so much easier:

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

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