node.js - How to await and return the result of a http.request(), so that multiple requests run serially? -
assume there function dorequest(options)
, supposed perform http request , uses http.request()
that.
if dorequest()
called in loop, want next request made after previous finished (serial execution, 1 after another). in order not mess callbacks , promises, want use async/await pattern (transpiled babel.js run node 6+).
however, unclear me, how wait response object further processing , how return result of dorequest()
:
var dorequest = async function (options) { var req = await http.request(options); // need "await" here somehow? req.on('response', res => { console.log('response received'); return res.statuscode; }); req.end(); // make request, returns boolean // return result here?! };
if run current code using mocha using various options http requests, of requests made simultaneously seems. fail, because dorequest()
not 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
work promises. work if async
function await
ing returns promise.
to solve problem, can either use library request-promise
or return promise dorequest
function.
here solution using latter.
async 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) { throw err; } }); }); });
Comments
Post a Comment