英文:
In reactJS how to wait for one api call to execute and then call next api
问题
在ReactJS中,如何等待一个API调用执行完毕,然后再调用下一个API。
在我的componentDidMount
生命周期方法中,我正在检查数据长度。一旦长度超过4,在这种情况下,我首先想保存数据,然后再检索数据。
componentDidMount = () => {
try {
MyApi.getInstance()
.count()
.then(async (data: any) => {
await this.saveDefaultData(); // await is not working
this.getData();
});
} catch (error) {}
}
saveDefaultData = () => {
try {
MyApi.getInstance().saveSystemDefault();
} catch (error) {}
};
getData = () => {
try {
MyApi.getInstance()
.getAllData()
.then((data: any) => {
// 状态更新操作
})
.catch();
} catch (error) {
// 错误处理
}
};
但是两个调用都是并行执行的,如何使它们按顺序执行。
英文:
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.
答案1
得分: 1
await
不起作用是因为没有声明返回值,因此没有承诺可供 await
。如果将 saveDefaultData
函数更改为 return MyApi.getInstance().saveSystemDefault();
,它将等待承诺解析。异步函数需要返回值才能正确等待。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论