Can I return results from npm async parallel inside a function

时间:2017-04-06 17:11:51

标签: node.js async.js

I would like to return the results from the npm async in nodejs, it returns undefined when I call the function 'findRequestAgent'

findRequestAgent : (agentId) => {
   var queries = [];
   var datum;
   queries.push((callback) => {
    MovingAgent.findById(agentId,(err,doc) => {
        if (err) {
            console.log("There was an error finding the moving agent");
            throw err;
        }

        callback(null, doc)
    })
   });

   queries.push((callback) => {
     SelfStander.findOne({ user_id: agentId}, (err, doc) => {
        if (err) {
            console.log("There was an error finding the self stander");
            throw err;                
        }

        callback(null, doc)
     })
   });

   queries.push((callback) =>{
     MovingCompany.findOne({custom_id: agentId}, (err, doc) => {
        if (err) {
            console.log("There was an error finding the self stander");
            throw err;                
        }

        callback(null, doc);
     })
   });

   async.parallel(queries, (err, results) => {
        if (err) {
            console.log("There was an error perfoming async");
            throw err;                
        }
        datum = results;
       console.log(datum);
   });

   return datum;
}

What can I do so that when I call the above function 'findRequestAgent' it returns the results

2 个答案:

答案 0 :(得分:1)

As a general rule, asynchronous functions don't return values directly. You need to use another mechanism such as a callback, events, promises.

Without knowing more about your use case, it's hard to know what the right solution is. But you should definitely stop and make sure you understand how asynchronous functions work in JavaScript before continuing.

The easiest solution is to do what you need to do in side the callback passed to .parallel() but again, without knowing more, it can't be said for certain that that will work for your use case.

答案 1 :(得分:1)

所有Mongo查询都会返回承诺。

var queries = [];

queries.push(
  MovingAgent.findById(agentId,(err,doc) => {
      if (err) {
          console.log("There was an error finding the moving agent");
          throw err;
      }

      return (null, doc);
  })
);

...

return Promise.all(queries).then(
  (results) => results; //array of results
).catch(
  (err) => console.log(err);
)

不需要异步部分