【发布时间】:2021-01-28 05:00:05
【问题描述】:
我正在尝试写一个这样的简单函数
const joinLeague = async () => {
const league = await attemptToJoinLeaugeIfItExists({ id, leaguePin })
console.log(league, 'fl')
if (league) {
// do something
}
}
我已经做了一个这样的 firebase 助手
export const attemptToJoinLeaugeIfItExists = ({ id, leaguePin }: any) => {
return new Promise((res, rej) => {
res(
firebaseApp
.database()
.ref(`users/${id}`)
.once('value')
.then((snapshot) => { `
firebaseApp
.database()
.ref(`leagues`)
.once('value')
.then((snapshot) => {
console.log('in here')
})
}),
)
})
}
然而,league 正在注销为未定义,in here 正在第二次注销。但是,我认为情况会相反?我认为它会“等待”此功能解决,然后一旦解决,它就会向我显示结果。我做错了什么?
【问题讨论】:
-
您是否已经在尝试调用时尝试使用
then()函数? -
您使用的是explicit promise constructor antipattern。你不需要它,你只需要做
return firebaseApp.database().ref(/* ... */).once(/* ... */).then(/* ... */) -
另外,在
.then()中嵌套另一个对firebaseApp的调用可能是不正确的。我怀疑有更好的方法来构建它,但我不熟悉 firebase,而且我什至不确定你为什么需要它。 -
您应该使用标准命名约定
resolve/reject而不是res/rej。 -
@Bibberty
res收到一个承诺,因此整个结果将等待该承诺首先解决。如果结果是另一个承诺,承诺会自动展平/合并。
标签: javascript reactjs promise async-await