How to await and return the result of a http.request(), so that multiple requests run serially?
async/await
work with promises. They will only work if the async
function your are await
ing returns a Promise.
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...');
}
});
});
});