在onSubmit中发起呼叫

我是新来的asynch,我想用asynch用firebase,一旦标记设置我想射击的动作,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使用我的功能?


小怪兽爱吃肉
浏览 176回答 2
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.

慕妹3242003

您还需要对await函数进行调用:async onSubmit(e) {&nbsp; &nbsp; //&nbsp; <-- add "async" here&nbsp; &nbsp; const {&nbsp; &nbsp; &nbsp; &nbsp; navigation: { navigate },&nbsp; &nbsp; &nbsp; &nbsp; credentials: { year, group, student },&nbsp; &nbsp; &nbsp; &nbsp; fetchEvents&nbsp; &nbsp; } = this.props;&nbsp; &nbsp; // for that matter, this here being called "AsyncStorage" suggests&nbsp;&nbsp; &nbsp; // that you *might* want to await this too.&nbsp; &nbsp; AsyncStorage.setItem(&nbsp; &nbsp; &nbsp; &nbsp; "loggedIn",&nbsp; &nbsp; &nbsp; &nbsp; JSON.stringify(this.props.credentials)&nbsp; &nbsp; );&nbsp; &nbsp; const token = await this.setToken();&nbsp; //&nbsp; <-- add "await" here&nbsp; &nbsp; if (token) {&nbsp; &nbsp; &nbsp; &nbsp; fetchEvents(student || group);&nbsp; &nbsp; &nbsp; &nbsp; navigate("Month");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript