I am trying to write a simple function like this
JavaScript
x
9
1
const joinLeague = async () => {
2
const league = await attemptToJoinLeaugeIfItExists({ id, leaguePin })
3
console.log(league, 'fl')
4
5
if (league) {
6
// do something
7
}
8
}
9
and I have made a firebase helper like this
JavaScript
1
20
20
1
export const attemptToJoinLeaugeIfItExists = ({ id, leaguePin }: any) => {
2
return new Promise((res, rej) => {
3
res(
4
firebaseApp
5
.database()
6
.ref(`users/${id}`)
7
.once('value')
8
.then((snapshot) => { `
9
firebaseApp
10
.database()
11
.ref(`leagues`)
12
.once('value')
13
.then((snapshot) => {
14
console.log('in here')
15
})
16
}),
17
)
18
})
19
}
20
however, league
is logging out as undefined and in here
is logging out second. however, I thought it would be the other way around? I thought it would “await” for this function to resolve then once it’s resolved, it would show me the result. what am I doing wrong?
Advertisement
Answer
do it like this:
JavaScript
1
13
13
1
export const attemptToJoinLeaugeIfItExists = ({ id, leaguePin }: any) => {
2
return firebaseApp
3
.database()
4
.ref(`users/${id}`)
5
.once('value')
6
.then((snapshot) => { `
7
return firebaseApp
8
.database()
9
.ref(`leagues`)
10
.once('value')
11
})
12
}
13
you’re currently immediately resolving your outer promise but with an inner promise, and that inner promise doesn’t return anything at all, hence undefined. Just return the promise directly. Cleaner, simpler.