简体   繁体   English

为什么这个承诺返回未定义?

[英]Why is this promise returning undefined?

I am trying to write a simple function like this我正在尝试编写一个像这样的简单函数

const joinLeague = async () => {
    const league = await attemptToJoinLeaugeIfItExists({ id, leaguePin })
    console.log(league, 'fl')

    if (league) {
        // do something 
    }
}

and I have made a firebase helper like this我做了一个像这样的火力助手

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')
                        })
                }),
        )
    })
}

however, league is logging out as undefined and in here is logging out second.然而, league以未定义的身份注销, in here是第二个注销。 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?我究竟做错了什么?

do it like this:像这样做:

export const attemptToJoinLeaugeIfItExists = ({ id, leaguePin }: any) => {
    return firebaseApp
                .database()
                .ref(`users/${id}`)
                .once('value')
                .then((snapshot) => { `
                    return firebaseApp
                        .database()
                        .ref(`leagues`)
                        .once('value')
                })
}

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.更干净,更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM