2017-09-17 61 views
0

雖然我等待接收關於是否應該跳過介紹的響應,但它會在開始處運行具有I設置值的if語句。下面是代碼:暫停執行代碼,直到異步函數返回所需的值

componentWillMount(){ 
    console.log("Intro component will mount:"); 
    let skipIntro = false; 
    this.checkSkipIntro() 
     .then((response)=>{ 
      skipIntro=response; 
      console.log("skipIntro is inside Async: " + skipIntro); 
    }); 
    console.log("skipIntro is: " + skipIntro); 
    if(skipIntro){ 
     console.log("skipping Intro"); 
     Actions.login(); 
    } 
} 
async checkSkipIntro() { 
    let skipIntro = await AsyncStorage.getItem("skipIntro"); 
    console.log("Skip Intro: " + skipIntro); 
    if (skipIntro === "yes"){ 
     console.log("returning True"); 
     return true; 
    } 
    else{ 
     console.log("returning False"); 
     return false; 
    } 
} 

日誌打印出:

Intro.js:9 Intro component will mount: 
Intro.js:16 skipIntro is: false 
Intro.js:37 Skip Intro: yes 
Intro.js:39 returning True 
Intro.js:14 skipIntro is inside Async: true 

如果您在調試器公告,console.log("skipIntro is: " + skipIntro); 在Intro.js:16個運行的console.log("skipIntro is inside Async: " + skipIntro); 在Intro.js之前: 14。我不確定如何暫停代碼的執行,直到函數返回適當的值。

我希望日誌輸出:

Intro.js:9 Intro component will mount: 
Intro.js:14 skipIntro is inside Async: true 
Intro.js:37 Skip Intro: yes 
Intro.js:39 returning True 
Intro.js:16 skipIntro is: true 

回答

1

要暫停,直到響應降臨時,你需要將代碼轉移到回調方法或承諾內.then方法內。

改變了...

componentWillMount(){ 
 
    console.log("Intro component will mount:"); 
 
    let skipIntro = false; 
 
    this.checkSkipIntro() 
 
     .then((response)=>{ 
 
      skipIntro=response; 
 
      console.log("skipIntro is inside Async: " + skipIntro); 
 
    }); 
 
    console.log("skipIntro is: " + skipIntro); 
 
    if(skipIntro){ 
 
     console.log("skipping Intro"); 
 
     Actions.login(); 
 
    } 
 
}

要這個......

componentWillMount(){ 
 
    console.log("Intro component will mount:"); 
 
    let skipIntro = false; 
 
    this.checkSkipIntro() 
 
     .then((response)=> { 
 
      skipIntro=response; 
 
      console.log("skipIntro is inside Async: " + skipIntro); 
 
      
 
      console.log("skipIntro is: " + skipIntro); 
 
      
 
      if(skipIntro){ 
 
       console.log("skipping Intro"); 
 
       Actions.login(); 
 
      } 
 
    }); 
 
}

因爲如果你注意到了。

此代碼從未運行!

if(skipIntro){ 
 
     console.log("skipping Intro"); 
 
     Actions.login(); 
 
    }

因爲skipIntro是假的,當它跑了。

簡單的概念是,當JavaScript還在等待承諾實現時,JavaScript運行了其他所有事情。

然後它回到.then方法當承諾響應來了。

所以如果你想等待一個響應導航/調用其他功能,你可以在.then函數或回調函數中執行。