Node.js - wait for multiple async calls

前端 未结 5 1532
自闭症患者
自闭症患者 2020-12-01 07:33

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 rend

5条回答
  •  盖世英雄少女心
    2020-12-01 08:26

    This seems like the least lines of code using await:

    var async = require("async"); //include async module
    ...
    async function getData() { //make sure to use async function
      var NYlakes = await db.collection('lakes').find(filterNY); //can append additional logic after the find() 
      var NJlakes = await db.collection('lakes').find(filterNJ);
    
      res.json({"NYLakes": NYLakes, "NJLakes": NJLakes}); //render response
    }
    
    getData();
    

    Side note: In this case await is serving as a Promise.all() be careful not to abuse the await function.

提交回复
热议问题