Javascript 暂停代码的执行,直到异步函数返回所需的值
当我等待是否应该跳过简介的响应时,它使用我在开头设置的值运行if语句。代码如下:Javascript 暂停代码的执行,直到异步函数返回所需的值,javascript,reactjs,asynchronous,react-native,async-await,Javascript,Reactjs,Asynchronous,React Native,Async Await,当我等待是否应该跳过简介的响应时,它使用我在开头设置的值运行if语句。代码如下: componentWillMount(){ console.log("Intro component will mount:"); let skipIntro = false; this.checkSkipIntro() .then((response)=>{ skipIntro=response; console.log
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是:”+skipIntro)代码>
在Intro.js:16中,在console.log之前运行(“skipIntro在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
要暂停直到收到响应,您需要将代码移到回调方法或中。然后将方法移到承诺中
改变这个
componentWillMount(){
log(“将装入的简介组件:”);
设skipIntro=false;
this.checkSkipIntro()
。然后((响应)=>{
skipIntro=响应;
log(“skipIntro在Async内:+skipIntro”);
});
log(“skipIntro是:“+skipIntro”);
如果(skipIntro){
log(“跳过介绍”);
Actions.login();
}
}