等待多个异步调用

等待多个异步调用

本文介绍了Node.js - 等待多个异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在渲染Jade模板之前创建多个MongoDB查询,但我无法弄清楚如何在渲染模板之前等待所有Mongo查询完成。

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
    });

};


推荐答案

我是下划线/ lodash的粉丝,所以我通常在之后使用 _。这会创建一个只在被调用一定次数后执行的函数。

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
}

因为javascript提升了用<$ c定义的函数的定义$ c> function funcName()语法,你的代码自然读取:从上到下。

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

这篇关于Node.js - 等待多个异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:10