我正在构建函数以等待on('value')中的所有值都被设置然后转到下一行,换句话说是异步函数。
let upcomingGamesList = await firebase.database().ref('UpcomingGames').on('value', snapshot => {
upcomingGamesList = snapshot.val()
console.log('upcoming t1',upcomingGamesList)
return upcomingGamesList
})
console.log('upcoming t2',upcomingGamesList)
let upcomingPreferences = upcomingGamesList.map(async(game) => {
console.log(game)
let GameId = game.GameId
await firebase.database().ref(`GameNotificationPreferances/${GameId}`).orderByKey().equalTo(UserStore.user.uid).once('value', snapshot => {
if (snapshot.val() != null || snapshot.val() != undefined) {
conosle.log(snapshot.val())
} else {
console.log('not value')
}
})
console.log(game)
})
发生的事情是即将到来的t2
console.log('upcoming t2',upcomingGamesList)
在即将到来的t1之前打印
console.log('upcoming t2',upcomingGamesList)
但是我在这个函数中使用了等待
let upcomingGamesList = await firebase.database().ref('UpcomingGames').on('value', snapshot => {
upcomingGamesList = snapshot.val()
console.log('upcoming t2',upcomingGamesList)
return upcomingGamesList
})
它应该等到完成然后转到下一行
我想等到函数完成后再使用我做过的更改获取updatedList
let upcomingGamesList = await firebase.database().ref('UpcomingGames').on('value', async(snapshot) => {
upcomingGamesList = snapshot.val()
updatededList = await upcomingGamesList.map(async(game) => {
let GameId = game.GameId
await firebase.database().ref(`GameNotificationPreferances/${GameId}`).orderByKey().equalTo(UserStore.user.uid).once('value', async(snapshot) => {
if (snapshot.val() != null || snapshot.val() != undefined) {
game['reminderPressed'] = true;
} else {
game['reminderPressed'] = false
}
console.log('GameId:',GameId, 'GameDetails:',game)
return ({...game})
})
})
})
console.log('the updatedList is',updatededList)
答案 0 :(得分:5)
Firebase的on()
功能会持续收听您呼叫他们的位置。这意味着他们可以多次为您提供数据。由于Promise
只能解析一次,on()
不会返回承诺。因此,它不能与async
/ await
一起使用。
在这种情况下,您似乎想要使用once()
,它的工作方式几乎相同,但只会传递一次结果(从而返回一个承诺):
let upcomingGamesList = await firebase.database().ref('UpcomingGames').once('value', snapshot => {
upcomingGamesList = snapshot.val()
console.log('upcoming t2',upcomingGamesList)
return upcomingGamesList
})
答案 1 :(得分:0)
这对我有用
export const deviceLogin = async (pin) => {
var ref = firebase.database().ref(`/devices/${pin}`);
const snapshot = await ref.once('value');
return snapshot.val();
}