skip to Main Content

I am a React noob and have a React component with a couple of functions that have API calls inside. I want to then call those functions from a separate onSubmit function and make another API call, but I don’t want to run the third API call until the first two have finished.

The code is set up like this:

function 1 (){
     fetch APIcall
     .then....
}

function 2 (){
     fetch APIcall
     .then....
}

function onSubmit(){
     function1()
     function2()
     fetch APIcall()     // don't want to run this until the other 2 calls are completed
     .then... 
}

I tried making function 1 and function2 async functions, but then I wasn’t sure how to await the promises in the onSubmit() function. Can this be done with async await, or is there a better way to handle this?

2

Answers


  1. use async await

    async function apiCall() {
      await function1();
      await function2();
      await function3();
    }
    

    by using async/await, you can wait one one api response before another api call

    Login or Signup to reply.
  2. You have two methods for handling multiple API calls. The first runs
    sequentially, while Promise.all executes concurrently. Choose the
    method that best fits your needs.

    Sequential Execution (awaiting each function):

    async function onSubmit() {
          await function1();
          await function2();
          await function3();
        }
    

    Concurrent Execution (Promise.all()):

    await Promise.all(
    [function1(), function2(), function3()]
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search