CoD*_*anX 14 httprequest mocha.js node.js async-await 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?!
};
Run Code Online (Sandbox Code Playgroud)
如果我使用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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
mkh*_*yan 24
async/await与承诺一起工作.它们只有在async你正在使用的函数await返回Promise 时才有效.
要解决您的问题,您可以使用类似的库,也可以request-promise从doRequest函数中返回一个promise .
这是使用后者的解决方案.
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...');
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
小智 5
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);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21249 次 |
| 最近记录: |