3

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

B组件由以下 Node.js 片段表示。

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

body我需要作为remoterequest函数的结果返回内容。我注意到,目前,POST 请求是异步的。因此,在将returnedvalue变量返回给调用方法之前,永远不会分配变量。

如何执行同步 HTTP 请求?

4

1 回答 1

3

您正在使用restifywhich 将promise在调用其方法(postget..etc)时返回。但是您创建的方法remoterequest不会返回promise让您等待使用.then. promise您可以使用async-await或内置返回,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;
    }
    
于 2018-05-21T12:17:42.600 回答