简体   繁体   中英

minimal node.js synchronous wait on http request

Consider a node.js loop to fire off http requests, like this:

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. My question is how do I synchronously wait on the "Sent" object returned from sendOne using the built in Node primitives.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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