我是async await
的新手 - 我试图在我的const tokenSet = await setToken(credentials);
动作中使用fetchEvents
,但是,tokenSet
总是未定义的。
如何将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;
});
}
}
我在这里使用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));
});
}
};
}
试试这个 :
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;
}