node.js 如何等待并返回 http.request() 的结果,以便多个请求串行运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41470296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to await and return the result of a http.request(), so that multiple requests run serially?
提问by CodeManX
Assume there is a function doRequest(options), which is supposed to perform an HTTP request and uses http.request()for that.
假设有一个函数doRequest(options),它应该执行一个 HTTP 请求并http.request()用于该请求。
If doRequest()is called in a loop, I want that the next request is made after the previous finished (serial execution, one after another). In order to not mess with callbacks and Promises, I want to use the async/await pattern (transpiled with Babel.js to run with Node 6+).
如果doRequest()在循环中调用,我希望在上一个完成后发出下一个请求(串行执行,一个接一个)。为了不干扰回调和 Promise,我想使用 async/await 模式(用 Babel.js 转译以在 Node 6+ 上运行)。
However, it is unclear to me, how to wait for the response object for further processing and how to return it as result of doRequest():
但是,我不清楚如何等待响应对象进行进一步处理以及如何将其作为结果返回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?!
};
If I run my current code using mochausing various options for the HTTP requests, all of the requests are made simultaneously it seems. They all fail, probably because doRequest()does not actually return anything:
如果我使用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);
});
});
});
回答by mkhanoyan
async/awaitwork with promises. They will only work if the asyncfunction your are awaiting returns a Promise.
async/await与承诺一起工作。只有当async您正在使用的函数await返回 Promise 时,它们才会起作用。
To solve your problem, you can either use a library like request-promiseor return a promise from your doRequestfunction.
为了解决您的问题,您可以使用类似库request-promise或从您的doRequest函数返回一个承诺。
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...');
}
});
});
});
回答by LostJon
you should be able to just pass done to your itfunction. then, after an async req is done, you would add line done()after your asserts. If there is an error, you would pass it to the done function like done(myError)
您应该能够将 done 传递给您的it函数。然后,在异步请求完成后,您将在断言后添加done()行。如果有错误,你会将它传递给 done 函数,如done(myError)
https://mochajs.org/#asynchronous-codefor more info

