如何等待并返回http.request()的结果,以便多个请求以串行方式运行?

时间:2017-01-04 17:55:18

标签: node.js async-await httprequest mocha babeljs

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

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

但是,我不清楚如何等待响应对象进行进一步处理以及如何将其作为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()实际上没有返回任何东西:

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

4 个答案:

答案 0 :(得分:18)

async/await与承诺合作。它们仅在async函数await返回Promise时才有效。

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

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

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...');
      }
    });
  });
});

答案 1 :(得分:0)

你应该能够完成你的 it 功能。然后,在完成异步请求后,您将在断言后添加 done()行。如果出现错误,您可以将其传递给完成函数,如 done(myError)

https://mochajs.org/#asynchronous-code了解更多信息

答案 2 :(得分:0)

https.get('https://example.com', options, async res => {
    try {
        let body = '';
        res.setEncoding('utf-8');
        for await (const chunk of res) {
            body += chunk;
        }
        console.log('RESPONSE', body);
    } catch (e) {
        console.log('ERROR', e);
    }
});

答案 3 :(得分:0)

const axios = require('axios');

const url = "https://stackoverflow.com";
const {data} = await axios.get(url);
console.log("RES:" + data);