[英]minimal node.js synchronous wait on http request
考虑一个node.js循环来触发http请求,如下所示:
var http = require('http');
function sendOne(opts, body)
{
var post_options = {
...
}
var sender = http.request(post_options, function(res) {
// process response
});
sender.write(body)
sender.end()
return sender;
}
for( var i =0; i < maxUploadIterations; i++)
{
var body = // construct payload
var sent = sendOne(opts, body);
// somehow wait on sent...
}
请注意,http.request对象具有为处理响应而指定的回调函数。 我的问题是如何使用内置的Node原语同步等待sendOne返回的“已发送”对象。
我知道有很多框架可以处理此问题,例如Express和Futures,但是我想了解原始行为,而不是使用“魔术”框架。
是否可以采用“已发送”并在其上放置一个处理程序,如下所示:
var sent = ...
sent.on("complete", function() { ... } );
?
如果是这样,究竟是哪个处理程序以及如何使用它格式化循环?
另一个选择是使用老式的回调方法。
var http = require('http');
function sendOne(opts, body, next) {
var post_options = {
// ...
};
var sender = http.request(post_options, function (res) {
// process response
next();
});
sender.write(body);
sender.end();
}
var maxUploadIterations = 100;
function next(index) {
// termination condition
if (index >= maxUploadIterations) {
return;
}
// setup next callback
var nextCallback = next.bind(null, index + 1);
// get these from wherever
var opts = {};
var body = {};
sendOne(opts, body, nextCallback);
}
next(0);
如果之后还有更多工作要做,则可以将终止条件更改为调用其他内容,而不是返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.