In ReactJS如何等待一个API调用执行,然后调用下一个API。

huangapple go评论160阅读模式
英文:

In reactJS how to wait for one api call to execute and then call next api

问题

在ReactJS中,如何等待一个API调用执行完毕,然后再调用下一个API。

在我的componentDidMount生命周期方法中,我正在检查数据长度。一旦长度超过4,在这种情况下,我首先想保存数据,然后再检索数据。

  1. componentDidMount = () => {
  2. try {
  3. MyApi.getInstance()
  4. .count()
  5. .then(async (data: any) => {
  6. await this.saveDefaultData(); // await is not working
  7. this.getData();
  8. });
  9. } catch (error) {}
  10. }
  11. saveDefaultData = () => {
  12. try {
  13. MyApi.getInstance().saveSystemDefault();
  14. } catch (error) {}
  15. };
  16. getData = () => {
  17. try {
  18. MyApi.getInstance()
  19. .getAllData()
  20. .then((data: any) => {
  21. // 状态更新操作
  22. })
  23. .catch();
  24. } catch (error) {
  25. // 错误处理
  26. }
  27. };

但是两个调用都是并行执行的,如何使它们按顺序执行。

英文:

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.

  1. componentDidMount = () => {
  2. try {
  3. MyApi.getInstance()
  4. .count()
  5. .then(async (data: any) => {
  6. await this.saveDefaultData(); // await is not working
  7. this.getData();
  8. });
  9. } catch (error) {}
  10. }
  11. this.saveDefaultData = () => {
  12. try {
  13. MyApi.getInstance().saveSystemDefault();
  14. } catch (error) {}
  15. };
  16. this.getData = () => {
  17. try {
  18. MyApi.getInstance()
  19. .getAllData()
  20. .then((data: any) => {
  21. // state update operation
  22. .catch();
  23. } catch (error) {
  24. Error handling
  25. }
  26. });
  27. };

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

huangapple
  • 本文由 发表于 2023年3月7日 22:31:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定