简体   繁体   English

最小的node.js同步等待HTTP请求

[英]minimal node.js synchronous wait on http request

Consider a node.js loop to fire off http requests, like this: 考虑一个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...
}

Note that the http.request object has a callback function specified for handling the response. 请注意,http.request对象具有为处理响应而指定的回调函数。 My question is how do I synchronously wait on the "Sent" object returned from sendOne using the built in Node primitives. 我的问题是如何使用内置的Node原语同步等待sendOne返回的“已发送”对象

I understand there are multiple frameworks like Express and Futures that can handle this, but I want to understand the primitive behavior rather than using a "magic" framework. 我知道有很多框架可以处理此问题,例如Express和Futures,但是我想了解原始行为,而不是使用“魔术”框架。

Is it possible to take "Sent" and put a handler on it like this: 是否可以采用“已发送”并在其上放置一个处理程序,如下所示:

var sent = ...
sent.on("complete", function() { ... } );

?

If so, exactly which handler and how to format the loop with it? 如果是这样,究竟是哪个处理程序以及如何使用它格式化循环?

Another option, use old fashion callbacks... Though promises may be cleaner. 另一个选择是使用老式的回调方法。

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);

If you have more work to do afterwards, you can change the termination condition to call something else, rather than return. 如果之后还有更多工作要做,则可以将终止条件更改为调用其他内容,而不是返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM