在Node.js中并行调用函数 [英] Parallel function calls in Node.js

查看:152
本文介绍了在Node.js中并行调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Node.js中执行一些独立的数据库查询。在执行完所有查询后,应发送响应。我的第一次尝试如下所示:

  templateData = {}; 

model.getA(function(result){
templateData.A = result;

model.getB(function(result){
templateData。 B = result;

model.getC(function(result){
templateData.C = result;

response.send('template',templateData);
})
})
});

当然,Node.js中的这种方法根本不好,因为所有函数都是依次调用的我放弃了异步编程模式的优点。我是Node.js的新手,我还不清楚如何调用 getA() getB() getC()并行并在所有内容完成后发送响应。是否有一些非常简单和常见的方法来实现这一点? 使用 npm install async )

  async.parallel([
function(){...},
function(){...}
],callback);

https ://github.com/caolan/async#parallel



或者,您可以使用承诺

  Q.spread(
[model.getA(),model (b,c){
// set templateData
return templateData;
}
) 。然后(...);

(假设得到*()方法返回承诺)

I need to do a few independent database queries in Node.js. After all queries are executed, response should be sent. My first try looks like this:

templateData = {};

model.getA(function(result) {
    templateData.A = result;

    model.getB(function(result) {
        templateData.B = result;

        model.getC(function(result) {
            templateData.C = result;

            response.send('template', templateData);
        })
    })
});

Of course, this approach in Node.js is not good at all, because all functions are called sequentially and I'm loosing advantages of asynchronous programming pattern. I'm new to Node.js and it's still unclear to me how to call getA(), getB() and getC() in parallel and send response just after everything is finished. Is there some really simple and common way to achieve this?

解决方案

Use the async package: (npm install async)

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

https://github.com/caolan/async#parallel

Alternatively, you can use promises:

Q.spread(
    [ model.getA(), model.getB(), model.getC() ],
    function(a, b, c) {
        // set templateData
        return templateData;
    }
).then(...);

(assuming that the get*() methods return promises)

这篇关于在Node.js中并行调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆