我是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));
});
}
};
}
答案 0 :(得分:0)
尝试一下:
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;
}