Reputation: 1465
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
Upvotes: 0
Views: 759
Reputation: 302
All of the Mongo queries return promises.
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);
)
No need for the async part
Upvotes: 1
Reputation: 70065
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.
Upvotes: 1