Brad
Brad

Reputation: 3510

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?

Upvotes: 0

Views: 573

Answers (1)

Kevin Burdett
Kevin Burdett

Reputation: 2982

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.

Upvotes: 1

Related Questions