NodeJS – 发送多个请求并在一个callback中处理所有的响应
我试图find一种方法来发送多个请求(使用Express),并在一个函数中处理所有的响应。
这是我的代码:
// In router.js app.get('/api/FIRST_PATH', CALLBACK_FUNCTION_A ); // In CALLBACK_FUNCTION_A file : module.exports = function (req, response) { CALLBACK_FUNCTION_TO_SERVICE_A(); CALLBACK_FUNCTION_TO_SERVICE_B(); CALLBACK_FUNCTION_TO_SERVICE_C(); }
我的问题是发送请求CALLBACK_FUNCTION_TO_SERVICE_A,CALLBACK_FUNCTION_TO_SERVICE_B和CALLBACK_FUNCTION_TO_SERVICE_C,然后检索另一个函数中的所有结果来处理它们。
任何帮助将不胜感激。
您可以了解更多关于新的js标准并使用Promise
。
// In CALLBACK_FUNCTION_A file : module.exports = function (req, response) { var promises = [CALLBACK_FUNCTION_TO_SERVICE_A(), CALLBACK_FUNCTION_TO_SERVICE_B(), CALLBACK_FUNCTION_TO_SERVICE_C()]; Promise.all(promises).then( function(results) { //results is an array //results[0] contains the result of A, and so on }); }
当然, CALLBACK_FUNCTION_TO_SERVICE_A()
等需要返回Promise
对象。 你形成一个这样的function:
function asyncFunction(callback) { //... callback(result); }
你可以像这样创build一个Promise:
var p = new Promise(asyncFunction);
它将开始运行该function,并支持Promise界面。
因此,例如,要么使用request-promise
,要么可以做如下的事情:
function CALLBACK_FUNCTION_TO_SERVICE_A() { var worker = function(callback) { app.get('/api/FIRST_PATH', callback); }; return new Promise(worker); }
您可以阅读更多关于Promise
以及如何轻松处理错误。
你可以使用asynchronous并行 。 您可以将所有API调用保存为async.parallel
数组或JSON(示例使用Array)。
async.parallel( [ function(done){ reqServcieA(..., funnction(err, response){ if(err) done(err,null); done(null, response); } }, function(done){ reqServcieA(..., funnction(err, response){ if(err) done(err,null); done(null, response); } }, ...// You can keep as many request inside the array ], function(err,results){ // Will be called when all requests are returned //results is an array which will contain all responses as in request arry //results[0] will have response from requestA and so on });