【问题标题】:NodeJS - Send multiple requests and process all responses in one callbackNodeJS - 在一个回调中发送多个请求并处理所有响应
【发布时间】:2016-10-02 00:03:24
【问题描述】:

我正在尝试找到一种方法来发送多个请求(使用 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,然后在另一个函数中检索所有结果来处理它们。

任何帮助将不胜感激。

【问题讨论】:

  • 使用request-promise 执行返回承诺的请求,然后在这些承诺完成时执行某些操作

标签: node.js express asynchronous


【解决方案1】:

您可以了解更多关于新 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 asyncFunction(callback) {
   //...
   callback(result);
}

你可以像这样创建一个 Promise:

var p = new Promise(asyncFunction);

会开始运行函数,并且支持Promise接口。

例如,要么使用request-promise,要么你可以这样做:

function CALLBACK_FUNCTION_TO_SERVICE_A() {
   var worker = function(callback) {
       app.get('/api/FIRST_PATH', callback);
   };

   return new Promise(worker);
}

您可以阅读有关Promise 以及如何轻松处理错误的更多信息。

【讨论】:

  • 令人兴奋!非常感谢
【解决方案2】:

您可以使用async parallel。您可以将所有 API 调用保留为 async.parallel 数组或 JSON(示例使用数组)。

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

【讨论】:

  • 我曾尝试使用异步并行。我想我没有正确使用它。谢谢你的回答。
猜你喜欢
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多