In reactJS how to wait for one api call to execute and then call next api.
In my componentDidMount I am checking data length. Once the length is more than 4 in that case first I want to save and then I want to retrieve.
componentDidMount = () => {
try {
MyApi.getInstance()
.count()
.then(async (data: any) => {
await this.saveDefaultData(); // await is not working
this.getData();
});
} catch (error) {}
}
this.saveDefaultData = () => {
try {
MyApi.getInstance().saveSystemDefault();
} catch (error) {}
};
this.getData = () => {
try {
MyApi.getInstance()
.getAllData()
.then((data: any) => {
// state update operation
.catch();
} catch (error) {
Error handling
}
});
};
But both the call is going parlay how to make it sequentially.
>Solution :
The await is not working because no return value is being declared so it has no promise to await if you change your saveDefaultData function to return MyApi.getInstance().saveSystemDefault(); it will wait for the promise to resolve. Async functions need a return value to be awaited properly