dhawalm
dhawalm

Reputation: 15

Async API Fetch in React JS

I have created two POST services in nodeJS express

Both above service give a response

I have to create a React JS app to fetch both the services. But I require that when we call both services simultaneously, the second service shouldn't wait for the first service to complete.

Below is my call for the service in REACT JS

const loadOrders = () =>{
   fetch("http://localhost:3001",{
     method:'POST',
     body: JSON.stringify({orderReferenceCode: 'GBP-000237453'}),
     headers: {
      "Content-type": "application/json; charset=UTF-8"
     }
     })
   .then(res => (res.ok ? res : Promise.reject(res)))
   .then(res => res.json())
 }

 const loadOrdersDetails = () =>{
   fetch("http://localhost:3001/details",{
     method:'POST',
     headers: {
      "Content-type": "application/json; charset=UTF-8"
     }
     })
   .then(res => (res.ok ? res : Promise.reject(res)))
   .then(res => res.json())
 }

What can I do to async this call's???

Upvotes: 0

Views: 475

Answers (3)

dglozano
dglozano

Reputation: 6607

If you just call them one after the other, as Mario Vernari suggested on the other answer, you will be calling both of them simultaneously (meaning the second call won't wait for the first one to be finished before being sent).

What I wanted to add is that you probably want to fire both request simultaneosly, in parallel, but then wait for both of them to finish to do something with the result of both of them.

In order to do that, there two approaches:

Using Promise.all

Promise.all([
  loadOrders(),
  loadOrdersDetails(),
]).then(([orderCode, orderDetails]) => {
    // Do something
}).catch((err) => {
    console.log(err);
}); 

Using async/await

try {
  let [orderCode, orderDetails] = await Promise.all([
    loadOrders(),
    loadOrdersDetails(),
  ]);

    // Do something
  );
}
catch(err) {
  console.log(err);
};

Additionally, you should make both load functions to return a Promise instead.

Upvotes: 0

Anku Singh
Anku Singh

Reputation: 954

You can use promise.all this will make sure that both the API's will get executed independently and also you will get result after both these API's get executed

 //first api which is returning promise

 const loadOrders = () =>{
   new Promise((resolve, reject) => {
        fetch("http://localhost:3001",{
          method:'POST',
          body: JSON.stringify({orderReferenceCode: 'GBP-000237453'}),
      headers: {
          "Content-type": "application/json; charset=UTF-8"
      }
        })
   .then(res => (res.ok ? res : reject(res)))
   .then(res => resolve(res.json()))
   });
   
 }

 //second api which is returning promise
 const loadOrdersDetails = () =>{
   new Promise((resolve, reject) => {
        fetch("http://localhost:3001/details",{
          method:'POST',
      headers: {
          "Content-type": "application/json; charset=UTF-8"
      }
     })
     .then(res => (res.ok ? res : reject(res)))
     .then(res => resolve(res.json()))
   })
 }
 
 Promise.all([loadOrders, loadOrdersDetails]).then((res) => {
    //here in res you will get reponse in array as output json from both the api [{},{}]
});

Upvotes: 1

Mario Vernari
Mario Vernari

Reputation: 7304

As simple as:

loadOrders();
loadOrdersDetails();

The function are called in sequence, but the effective flow it depends on the callback, which will be asynchronous.

However, you must take an appropriate approach for the UI in order to manage the results, if you need them.

Upvotes: 0

Related Questions