暂停执行代码,直到异步函数返回所需的值

时间:2017-09-17 03:45:39

标签: 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("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:在console.log("skipIntro is inside Async: " + skipIntro);之前运行16次  在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 个答案:

答案 0 :(得分:1)

要暂停直到响应出现,您需要将代码转移到回调方法或promise中的.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在运行时为false。

简单的概念是当JavaScript仍在等待履行承诺时,JavaScript会运行其他所有内容。

当承诺响应到来时,它又回到了.then方法。

因此,如果您想等待响应导航/调用其他功能,请在.then函数或回调函数中执行。