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 }); };
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With