如何处理需要两个asynchronous方法的node / express的请求

我正在学习节点。 我有一个web应用程序,通过比特币包与bitcoind连接,通过knex与PostgreSQL 连接 。 我需要从每个模块获取一些数据,然后将其全部传递给我的视图进行渲染。 我的代码看起来像这样到目前为止:

exports.index = function(req, res){ var testnet=''; bitcoin.getInfo(function(e, info){ if(e){ return console.log(e);} if(info.testnet){ testnet='bitcoin RPC is testnet'; }else{ testnet='nope.. you must be crazy'; } var c=knex('config').select().then(function(k){ res.render('index', { title: k[0].site_name, testnet: testnet }); }); }); }; 

这样做的结构方式,首先等待比特币回复,然后将请求发送到PostgreSQL,然后等待一段时间回复。 这两个等待期可能会同时发生。 但是,我不知道如何做与承诺/callback在Javascript中。 我怎样才能pipe理这种asynchronous发生,而不是连续发生?

您需要promisifycallback方法,不混合callback和承诺。

 var Promise = require("bluebird"); var bitcoin = require("bitcoin"); //Now the bitcoin client has promise methods with *Async postfix Promise.promisifyAll(bitcoin.Client.prototype); var client = new bitcoin.Client({...}); 

那么实际的代码是:

 exports.index = function(req, res) { var info = client.getInfoAsync(); var config = knex('config').select(); Promise.all([info, config]).spread(function(info, config) { res.render('index', { title: config[0].site_name, testnet: info.testnet ? 'bitcoin RPC is testnet' : 'nope.. you must be crazy' }); }).catch(function(e){ //This will catch **both** info and config errors, which your code didn't //do console.log(e); }); }; 

使用承诺模块蓝鸟 。

你正在寻找asynchronous模块,这将允许你发射这两个任务,然后继续。

一个未经testing的例子给你的想法:

 exports.index = function(req, res){ var testnet='', k={}; async.parallel([ function(){ bitcoin.getInfo(function(e, info){ //your getInfo callback logic }, function(){ knex('config').select().then(function(result) { //your knex callback k = result; } ], //Here's the final callback when both are complete function() { res.render('index', { title: k[0].site_name, testnet: testnet }); }); } 

你可以使用一个像caolan / async的#parallel()方法的库,或者你可以绕过它的源代码并学习自己的angular色