简体   繁体   English

异步函数返回未定义

[英]Async function returns undefined

I am new to async await - I am trying to use const tokenSet = await setToken(credentials);我是async await新手 - 我正在尝试使用const tokenSet = await setToken(credentials); in my fetchEvents action, however, tokenSet is always undefined.但是,在我的fetchEvents操作中, tokenSet始终未定义。

How can I return fcmToken as the value to use in my action?如何将fcmToken作为要在我的操作中使用的值返回?

async function setToken(credentials) {
    const { year, group, student } = credentials;
    const fcmToken = await firebase.messaging().getToken();

    if (fcmToken) {
        firebase
            .firestore()
            .collection("users")
            .doc(fcmToken)
            .set({
                year, group, student
            })
            .then(function(fcmToken) {
                return fcmToken;
            })
            .catch(function(error) {
                return null;
            });
    }
}

I am using the setToken function here:我在这里使用setToken函数:

export function fetchEvents(credentials) {
    const { year, group, student } = credentials;
    const currentDateString =
        moment().format("YYYY-MM-DD") + "T" + "07:00:00.000Z";
    const id = student || group;
    const url = `https://www.googleapis.com/calendar/v3/calendars/${id}/events?singleEvents=true&orderBy=startTime&timeMin=${currentDateString}&key=${key}`;

    return async dispatch => {
        dispatch(isLoading(true));
        console.log();
        const tokenSet = await setToken(credentials);

        if (tokenSet) { // always undefined
            fetch(url)
                .then(response => {
                    return response;
                })
                .then(response => response.json())
                .then(data => {
                    const { error } = data;
                    if (error) {
                        dispatch(hasErrored(error.message));
                    } else {
                        dispatch(fetchSuccessEvents(data.items));
                    }

                    navigate("Month");
                    dispatch(isLoading(false));
                });
        }
    };
}

Try this :尝试这个 :

async function setToken(credentials) {
    const { year, group, student } = credentials;
    const fcmToken = await firebase.messaging().getToken();

    if (fcmToken) {
        firebase
            .firestore()
            .collection("users")
            .doc(fcmToken)
            .set({
                year, group, student
            })
            .then(function(fcmToken) {
                return fcmToken;
            })
            .catch(function(error) {
                return null;
            });
        return true;
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM