Node.js - wait for multiple async calls

前端 未结 5 1529
自闭症患者
自闭症患者 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:16

    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.

提交回复
热议问题