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

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

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

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:

确定