NodeJs-HTTP-两个请求同步问题

时间:2018-11-12 13:19:27

标签: node.js http asynchronous promise synchronization

我需要执行两个http请求,我希望在两个单独的函数中具有这些请求。我同步地想:

..发出第一个http请求并返回响应

..将响应传递给第二个函数,该函数使第二个http-请求

第一个功能:

function getObjTypes(cfg) {

  // request-options
  var post_options = {
    host: cfg.apiHost,
    port: cfg.apiPort
  };

  // request
  var ObjectTypes = [];

  var post_req = http.request(post_options, function(res) {

    res.setEncoding('utf8');
    let resBody = '';

    res.on('data', function (chunk) {
      resBody += chunk;
    });

    res.on("end", () => {
      var resObject = JSON.parse(resBody);    

      return ObjectTypes; // Here the ObjectTyes needs to be passed as a return

    });
  });
  post_req.end(); 
}

我知道出什么问题了。.http请求是异步的,因此在第一个函数出现之前,第二个函数在响应之前被调用了。但是我将如何“修复”此问题?

0 个答案:

没有答案
相关问题