Reputation: 2392
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?
Upvotes: 0
Views: 94
Reputation:
Why not using 2 conditions?
if (dontMakeHttpReq1) {
request(req1, function(error, response, body) {
yourRequestProcessing2();
});
}
else {
request(req1, function(error, response, body) {
request(req2, function(error, response, body) {
yourRequestProcessing2();
});
yourRequestProcessing1();
});
}
Edit: Maybe you want to store the request calls in arrays
//Whether request n should skip
var flags = [
false,
true,
false
];
var requests = [
function(error, response, body) {
//Process your request 1
},
function(error, response, body) {
//Process your request 2
},
function(error, response, body) {
//Process request 3
}
];
for (i = 0; i < requests.length; i++) {
if (flags[i]) {
request(req1, requests[i + 1]);
}
else {
request(req2, request[i]);
}
}
Upvotes: 1
Reputation: 16440
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
}
}
Upvotes: 2
Reputation: 870
You can use async-await to achieve that.
async apiCall(){
try{
if(condition){
const result1 = await request(httpReq1);
}
const result2 = await request(httpReq2);
}
catch(error){
}
}
make sure that request module retruns a promise. Otherwise create a promise wrapper. axios is a library that is promise based.
You have to put async before the function that includes your awaits
Upvotes: 1