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

新手上路,请多包涵

假设有一个函数 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);
        });
    });
});

原文由 CodeManX 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

async/await 使用承诺。只有当 async 函数 your are 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...');
      }
    });
  });
});

原文由 mkhanoyan 发布,翻译遵循 CC BY-SA 3.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);
    }
});

原文由 Mike.Stanley 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题