【问题标题】:Synchronous HTTP requests in Node.jsNode.js 中的同步 HTTP 请求
【发布时间】:2018-10-31 02:20:46
【问题描述】:

我有三个组件ABC。 当AB 发送HTTP 请求时,BC 发送另一个HTTP 请求,检索相关内容并将其作为HTTP 响应发送回A

B 组件由以下 Node.js sn-p 表示。

var requestify = require('requestify');

// sends an HTTP request to C and retrieves the response content
function remoterequest(url, data) {
  var returnedvalue;
  requestify.post(url, data).then(function(response) {
    var body = response.getBody();
    // TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
  });
  return returnedvalue;
}

// manages A's request
function manageanotherhttprequest() {
  // [...]
  var res = remoterequest(url, data);
  // possible elaboration of res
  return res;
}

由于remoterequest 函数,我需要返回body 内容。 我注意到,目前,POST 请求是异步的。因此,returnedvalue 变量在返回给调用方法之前永远不会被赋值。

如何执行同步 HTTP 请求?

【问题讨论】:

    标签: node.js web-services http asynchronous requestify


    【解决方案1】:

    您正在使用restify,一旦调用它的方法(postget..etc),它将返回promise。但是您创建的方法remoterequest 没有返回promise 让您等待使用.then。您可以使用async-await 或内置promise 使其返回promise,如下所示:

    • 使用承诺:

      var requestify = require('requestify');
      
      // sends an HTTP request to C and retrieves the response content
      function remoterequest(url, data) {
        var returnedvalue;
        return new Promise((resolve) => {
          requestify.post(url, data).then(function (response) {
            var body = response.getBody();
            // TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
          });
          // return at the end of processing
          resolve(returnedvalue);
        }).catch(err => {
          console.log(err);
        });
      }
      
      // manages A's request
      function manageanotherhttprequest() {
        remoterequest(url, data).then(res => {
          return res;
        });
      }
      
    • 使用异步等待

      var requestify = require('requestify');
      
      // sends an HTTP request to C and retrieves the response content
      async function remoterequest(url, data) {
      
        try {
          var returnedvalue;
          var response = await requestify.post(url, data);
          var body = response.getBody();
          // TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
          // return at the end of processing
          return returnedvalue;
        } catch (err) {
          console.log(err);
        };
      }
      
      // manages A's request
      async function manageanotherhttprequest() {
          var res = await remoterequest(url, data);
          return res;
      }
      

    【讨论】:

    • 我不明白为什么它应该起作用。作为一个异步请求,函数内部的所有内容实际上都是在调用方法返回后执行的。
    • @auino,看到我更新的答案,如果您有任何问题,请回复。
    猜你喜欢
    • 2018-02-14
    • 2016-05-20
    • 1970-01-01
    • 2015-11-21
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多