What I would like to achieve is to execute synchronously an ordered sequence of HTTP requests, but depending on the value of some variables, I want some of them to be by-passed.
As an example (I am using the request
library in Javascript to do so):
request(httpReq1, function(error, response, body) {
// do something, like handling errors...
request(httpReq2, function(error, response, body) {
// do something else
});
});
So this ensures that httpReq2
will execute after httpReq1
.
What I am not sure is how to by-pass the first request if, for example, some flag is set to false, and instead of executing httpReq1
and wait for a response, it just jumps to httpReq2
, keeping the order:
if (dontMakeHttpReq1) // where should this be placed?
request(httpReq1, function(error, response, body) {
// do something, like handling errors...
request(httpReq2, function(error, response, body) {
// do something else
});
});
What would be a good approach to solve this?
Sort out a list of requests needed in an array, and execute them sequentially using the async/await
let requests = [];
if (doRequest1)
requests.push(httpReq1);
if (doRequest2)
requests.push(httpReq2);
/* etc .. for httpReq3 and so on */
// now execute them one by one in sequence
for(let req of requests) {
try {
await request(req);
} catch (err) {
// error handling here
}
}