Node.js的等待REST服务的回调,使HTTP请求 [英] Node.JS Wait for callback of REST Service that makes HTTP request

查看:440
本文介绍了Node.js的等待REST服务的回调,使HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用前preSS模块,使内Node.js的一个RESTful API在我的服务我作出额外的HTTP请求外端点(服务器端),我需要从这些http请求数据返回给我的web服务请求主体。

I am using express module to make a Restful API within Node.JS. In my service I am making additional http requests to outside Endpoints(server side) and I need to return the data from those http requests to my web service request body.

我已经证实,如果我使用的console.log 在所有的Web服务正在开展我得到我需要的数据的操作。然而,当我试图返回这些值的服务,他们回来了空。我知道,这是因为异步和回调是不是等待http请求来完成。

I have confirmed that if I use console.log on all the actions that the Web Service is conducting I am getting the data that I need. However, when I try to Return those values to the service they come back Null. I know that this is because of async and the callback is not waiting for the http request to finish.

有没有一种方法,使这项工作?

Is there a way to make this work?

推荐答案

一个常见的​​做法是使用异步模块。

A common practice is to use the async module.

npm install async

异步模块的原语来处理各种形式的异步事件。

The async module has primitives to handle various forms of asynchronous events.

在你的情况下,异步#并行通话将让你在同一时间发出请求所有外部的API,然后给你请求者合并结果的回报。

In your case, the async#parallel call will allow you to make requests to all external APIs at the same time and then combine the results for return to you requester.

既然你让外部的HTTP请求,你可能会发现申请模块也非常有帮助。

Since you're making external http requests, you will probably find the request module helpful as well.

npm install request

使用要求异步并行#您的路由处理会是这个样子......

Using request and async#parallel your route handler would look something like this...

var request = require('request');
var async = require('async');

exports.handler = function(req, res) {
  async.parallel([
    /*
     * First external endpoint
     */
    function(callback) {
      var url = "http://external1.com/api/some_endpoint";
      request(url, function(err, response, body) {
        // JSON body
        if(err) { console.log(err); callback(true); return; }
        obj = JSON.parse(body);
        callback(false, obj);
      });
    },
    /*
     * Second external endpoint
     */
    function(callback) {
      var url = "http://external2.com/api/some_endpoint";
      request(url, function(err, response, body) {
        // JSON body
        if(err) { console.log(err); callback(true); return; }
        obj = JSON.parse(body);
        callback(false, obj);
      });
    },
  ],
  /*
   * Collate results
   */
  function(err, results) {
    if(err) { console.log(err); res.send(500,"Server Error"); return; }
    res.send({api1:results[0], api2:results[1]});
  }
  );
};

您还可以了解其他的回调测序方法这里

You can also read about other callback sequencing methods here.

这篇关于Node.js的等待REST服务的回调,使HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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