Home > Back-end >  How can I conditionally make a series of HTTP requests from within a NodeJS script?
How can I conditionally make a series of HTTP requests from within a NodeJS script?

Time:01-20

I am using express and node to make a server side script that receives information from a form post and proceeds to then call a series of HTTP Requests to accomplish some tasks.

Now my problem is that the normal promise chain doesn't quite work here. There are cases where one request would be called and other cases when it wouldn't.

So something like

request1.then(request2.then(request3))) which would normally work doesn't if based upon the data in the form I don't actually need to do (and shouldn't do) request2. How can I make this without basically having code for every single permutation?

In other words is this possible to do without having to do

if(request1 && request2 && request3) {
    request1.then(request2.then(request3)))
} elseif (request1 && request2) {
    request1.then(request2))
} elseif (request1 && request3) {
    request1.then(request3)

etc..

After request1, the following requests are not strictly dependant on each other, so I tried something like

request1.then(
    if(request2) {
        request2.catch(err)
    }
    if(request3) {
        request3.catch(err)
    }
    if(request4)
        request4.catch(err)
    }
)

It turned out this doesn't seem to work and I am getting unhandledPromiseRejectionWarnings.

So I guess this wasn't the right path. Any ideas on this? I am using axios if it matters.

CodePudding user response:

Promise.allSettled()

You can use Promise.allSettled method which returns a single promise that resolves when all the input promises have been resolved (including when an empty iterable is passed). This is a better way to execute a series of promises instead of having multiple .then, .catches.

P.S. Promise.all() can also be used if you want to reject the promise if one of the request fails

DEMO:

/**
* Method to build an array of requests (promises)
*/
function promisesBuilder(request1Response) {
    const request2 = 1337;
    const request3 = request1Response === 4 ? fetch('https://catfact.ninja/fact') : null;
    const request4 = request1Response === 3 ? fetch('https://catfact.ninja/fact') : null;
    return [request2, request3, request4].filter(x => x); // Remove null values
}


async function executeRequests () {
    const request1 = new Promise((resolve, reject) => resolve(3));
    const request1Response = await request1; // this is your call Ex:  await axios.get()
    
    let resp = null;
    const promises = promisesBuilder(request1Response);
    if(request1Response) {
        resp = await Promise.allSettled(promises);
    }
    
    return resp;
}

const responses = executeRequests().then(res => console.log(res))

CodePudding user response:

You can use

 async.series([
  function(callback) {
    //request
    callback(request1);
  },
  function(callback) {
    //request
    callback(request2 );
  },
  function(callback) {
     //request 
    callback(request3);
  }
],
 (err, results) {
  console.log(result);
  if(err){
  //Handle  your error 
  }
});

To avoid callback Hell, you can execute your functions sequentially. If it happens that one function throws an error, the execution stops and the error is handled

  • Related