2017-09-17 3 views
0

イントロをスキップする必要があるかどうかの応答を受け取るのを待っていますが、最初に設定した値のif文が実行されます。以下のコードは次のとおりです。Intro.jsでconsole.log("skipIntro is inside Async: " + skipIntro); 前に16の実行:非同期関数が目的の値を返すまでコードの実行を一時停止します

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 

デバッガに気付いた場合、Intro.jsでconsole.log("skipIntro is: " + skipIntro); : 14。関数が適切な値を返すまで、コードの実行を一時停止する方法は不明です。

私が出力するログを期待:応答はあなたがコールバックメソッドまたは約束内部.thenメソッド内にコードをシフトする必要が来るまで

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

が一時停止します。

変更この...これに

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はfalseですので。

単純な概念では、JavaScriptはまだ約束が達成されるのを待っているときに、他のすべてを実行しました。

次に、約束応答が来たときに.thenメソッドに戻りました。

したがって、応答または他の機能を呼び出すのを待つ場合は、.then関数またはコールバック関数内で行います。

関連する問題