0

I have created two POST services in nodeJS express

  • http://localhost:3001 - This service has body request {order:"123"} with method POST & setTimeout for 5000
  • http://localhost:3001/details - This service doesn't have any body request or setTimeout

Both above service give a response

  • First Response is : Order Code:123
  • Second Response is JSON of Order Details: {'Date':'2020-05-12', 'amount':'20'}

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???

5
  • I know this is not what you asked, but are you sure you have to call loadOrdersDetails without waiting for loadOrders ? What if the first POST fails and the order doesn't get created? What order details will you be posting afterwards? Again, I have no idea about your application, but it seems to me that you need an "orderCode" to POST the orderDetails, if not you don't know which order the details belong to. Commented Jul 22, 2020 at 7:13
  • Hi Dglozano, No both service are not depended on each other.. but loadOrders will have wait for 5 secs & loadOrdersDetails is not waiting at all. Commented Jul 22, 2020 at 7:18
  • What do you mean by waiting ? How are you calling those functions? Commented Jul 22, 2020 at 7:20
  • I meant by waiting is that, second orderDetails service should run without the response from order service.. Commented Jul 22, 2020 at 7:54
  • And that's what should be happening if you just call them the way we pointed out in the answers. If it is still not working, you should upload the code that is calling those functions so we can further help :) Commented Jul 22, 2020 at 8:26

3 Answers 3

1

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 [{},{}]
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

so just calling the function like this will be async..?? it won't wait for loading the loadOrders??
when you call fetch, the request will start immediately, but also the fetch function itself is (let's say) over, and you exit from the function immediately. When the response arrives, then then method will be called.
0

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.

1 Comment

also true. It depends on (1) if the POSTs have an answer to deal with or not, and (2) if the desired behavior of the GUI is to wait both the responses, or just update a progression bar, for instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.