Mr.D Mr.D - 21 days ago 5
Javascript Question

Node JS, chaining variable number of http requests

I'm using

request js
library to make HTTP requests to my API. My single API call looks like this:

var options = {
method: "post",
url: 'http//example.com',
json: true,
headers: headers,
body: {key: value}
}
request(options, callback);


However, I have array of
options
, which are needed to be called one after another and I need to break whole chain if one of them fails.

If last chain finishes, I need to output result to console.

I know that chaining callbacks could be fulfilled via promises, but all examples that I have found uses predefined amount of chained requests.

Is it possible?

Answer

If you have an array, you can have an index into that array, and have the callback kick off the next request when the previous one finishes. Roughly:

var index = 0;
var options = [/*...array of options objects...*/];
doRequest() {
    request(options[index], function(err, result) {
        // ...handle the result/error here. If there's no error, then:
        if (++index < options.length) {
            // Kick off the next request
            doRequest();
        }
    });
}

While the above can be Promise-ified, since your requestmethod appears not to be, it would just complicate things.