Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - wait for multiple async calls

I'm trying to make multiple MongoDB queries before I render a Jade template, but I can't quite figure out how to wait until all the Mongo Queries are completed before rendering the template.

exports.init = function(req, res){       var NYLakes = {};     var NJLakes = {};     var filterNY = {"State" : "NY"};     db.collection('lakes').find(filterNY).toArray(function(err, result) {         if (err) throw err;         NYLakes = result;     });      var filterNJ = {"State" : "NJ"};     db.collection('lakes').find(filterNJ).toArray(function(err, result) {         if (err) throw err;         NJLakes = result;     });      res.render('explore/index', {             NYlakes: NYLakes,             NJlakes: NJLakes     });  }; 
like image 967
Warrick FitzGerald Avatar asked Aug 02 '13 03:08

Warrick FitzGerald


People also ask

How do you handle multiple asynchronous calls in node JS?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

Can async method have multiple awaits?

For more information, I have an async / await intro on my blog. So additionally, if a method with multiple awaits is called by a caller, the responsibility for finishing every statement of that method is with the caller.

How do you wait for async to finish?

The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.

How do you handle multiple promises in node JS?

Approach 1: In this approach, we will use Promise. all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.


1 Answers

I'm a big fan of underscore/lodash, so I usually use _.after, which creates a function that only executes after being called a certain number of times.

var finished = _.after(2, doRender);  asyncMethod1(data, function(err){   //...   finished(); });  asyncMethod2(data, function(err){   //...   finished(); })  function doRender(){   res.render(); // etc }  

Since javascript hoists the definition of functions defined with the function funcName() syntax, your code reads naturally: top-to-bottom.

like image 107
ssafejava Avatar answered Oct 02 '22 17:10

ssafejava