2017-09-17 1 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(); 
 
      } 
 
    }); 
 
}

원인

당신이 발견합니다.

이 코드는 실행되지 않습니다!

가 실행되었을 때 skipIntro이 거짓이기 때문에

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

단순한 개념은 JavaScript가 약속이 성취되기를 기다리고있을 때 다른 모든 것을 실행한다는 것입니다.

그런 다음 약속 응답이 왔을 때 .then 메소드로 돌아갔습니다.

응답을 받기 위해 기다리고 싶다면 .then 함수 또는 콜백 함수 내에서 다른 기능을 호출하거나 호출해야합니다.