在onSubmit中发起呼叫

时间:2019-03-27 13:46:05

标签: javascript

我是asynch的新手,我尝试将asynchfirebase一起使用,一旦设置了令牌,我想触发动作fetchEvents,并navigate

async setToken() {
    const fcmToken = await firebase.messaging().getToken();
    return fcmToken;
}

onSubmit(e) {
    const {
        navigation: { navigate },
        credentials: { year, group, student },
        fetchEvents
    } = this.props;

    AsyncStorage.setItem(
        "loggedIn",
        JSON.stringify(this.props.credentials)
    );

    const token = this.setToken();

    if (token) {
        fetchEvents(student || group);
        navigate("Month");
    }
}

如果我在调试器中检查token,那是一个承诺:

_40: 0
_55: null
_65: 0
_72: null

如何让asynch与我的功能一起使用?

2 个答案:

答案 0 :(得分:2)

每个async函数都返回Promise。就这么简单。

async setToken() {
    const fcmToken = await firebase.messaging().getToken();
    // Now if you console.log() the fcmToken will be string

    return fcmToken;
}

console.log(setToken()) 
// This will be promise and inside will be fcmToken, 
// because anything you return from async function will be wrapped in Promise.

答案 1 :(得分:0)

您还需要await函数调用:

async onSubmit(e) {    //  <-- add "async" here
    const {
        navigation: { navigate },
        credentials: { year, group, student },
        fetchEvents
    } = this.props;

    // for that matter, this here being called "AsyncStorage" suggests 
    // that you *might* want to await this too.
    AsyncStorage.setItem(
        "loggedIn",
        JSON.stringify(this.props.credentials)
    );

    const token = await this.setToken();  //  <-- add "await" here

    if (token) {
        fetchEvents(student || group);
        navigate("Month");
    }
}