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?
1
You can use javascript async/await.
async function onSubmit() {
// Call the first function
await firstFunction();
// Call the second function
await secondFunction();
// Call your final API
await finalAPI();
}
async function firstFunction() {
// APi call or any asynchronous operation
}
async function secondFunction() {
// APi call or any asynchronous operation
}
async function finalAPI() {
// APi call or any asynchronous operation
}
When you use await
, each function will wait for the previous one to finish.
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
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()]
);