1. 程式人生 > 實用技巧 >react 結合 Promise 和 async await 解決多個非同步請求 後統一設定狀態問題

react 結合 Promise 和 async await 解決多個非同步請求 後統一設定狀態問題

現在需要解決以下問題:

我們有兩個和多個前後端互動請求,我們需要在這兩個請求都完成之後去讓runder渲染,實現思路如下:

1、定義一個loading的state,給定初始值為true,在runder函式中,如果loading為true則直接返回

this.state = {
    loading: true
}

2、將兩個或多個請求使用Promist.all([]),做併發處理。

3、然後使用async await 等待請求處理完成後將loading置為false。

實現程式碼如下:

getAsyncData() {
    return Promise.all([
        
this.getCurriculumVitae(), this.growthPathDate() ]) } async asyncFun() { await this.getAsyncData() this.setState({loading: false}) } getCurriculumVitae() { return request.get('xxxx',{//這裡必須使用return返回非同步請求 params: { // } }).then((resp:any) => { if(resp && resp.code == "200" && resp.data){
this.setState({ // }) } }) } growthPathDate = () => { return request.get('xxxx',{//這裡必須使用return返回非同步請求 params: { // } }) .then((resp:any) => { if(resp && resp.code == '200' && resp.data) {
this.setState({ // }) } }) }