如何等待并返回http.request()的结果,以便多个请求串行运行? [英] How to await and return the result of a http.request(), so that multiple requests run serially?

查看:335
本文介绍了如何等待并返回http.request()的结果,以便多个请求串行运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个函数doRequest(options),该函数应该执行HTTP请求并为此使用http.request().

Assume there is a function doRequest(options), which is supposed to perform an HTTP request and uses http.request() for that.

如果在循环中调用doRequest(),我希望下一个请求在上一个完成(串行执行,一个接一个)之后发出.为了不使回调和Promises混乱,我想使用async/await模式(与Babel.js一起编译以与Node 6+一起运行).

If doRequest() is called in a loop, I want that the next request is made after the previous finished (serial execution, one after another). In order to not mess with callbacks and Promises, I want to use the async/await pattern (transpiled with Babel.js to run with Node 6+).

但是,我不清楚如何等待响应对象进行进一步处理以及如何将其作为doRequest()的结果返回:

However, it is unclear to me, how to wait for the response object for further processing and how to return it as result of doRequest():

var doRequest = async function (options) {

    var req = await http.request(options);

    // do we need "await" here somehow?
    req.on('response', res => {
        console.log('response received');
        return res.statusCode;
    });
    req.end(); // make the request, returns just a boolean

    // return some result here?!
};

如果我使用 mocha 并为HTTP请求使用各种选项来运行当前代码,那么看起来所有请求都是同时发出的.它们都失败了,可能是因为doRequest()实际上没有返回任何东西:

If I run my current code using mocha using various options for the HTTP requests, all of the requests are made simultaneously it seems. They all fail, probably because doRequest() does not actually return anything:

describe('Requests', function() {
    var t = [ /* request options */ ];
    t.forEach(function(options) {
        it('should return 200: ' + options.path, () => {
            chai.assert.equal(doRequest(options), 200);
        });
    });
});

推荐答案

async/await与promises一起工作.仅当您正在使用awaitasync函数返回一个Promise时,它们才起作用.

async/await work with promises. They will only work if the async function your are awaiting returns a Promise.

要解决您的问题,您可以使用request-promise之类的库,也可以使用doRequest函数返回诺言.

To solve your problem, you can either use a library like request-promise or return a promise from your doRequest function.

这是使用后者的解决方案.

Here is a solution using the latter.

function doRequest(options) {
  return new Promise ((resolve, reject) => {
    let req = http.request(options);

    req.on('response', res => {
      resolve(res);
    });

    req.on('error', err => {
      reject(err);
    });
  }); 
}

describe('Requests', function() {
  var t = [ /* request options */ ];
  t.forEach(function(options) {
    it('should return 200: ' + options.path, async function () {
      try {
        let res = await doRequest(options);
        chai.assert.equal(res.statusCode, 200);
      } catch (err) {
        console.log('some error occurred...');
      }
    });
  });
});

这篇关于如何等待并返回http.request()的结果,以便多个请求串行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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