为什么这个 Promise 返回 undefined?

3

我正在尝试编写一个像这样简单的函数

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 第二个返回。但是,我认为应该相反才对?我以为它会 "等待" 此函数解决,然后一旦解决了,它会显示结果。我做错了什么?


你是否已经尝试在attemptTo()调用中使用then()函数? - Yannick
你应该使用标准的命名约定 resolve/reject 而不是 res/rej - jarmod
你的辅助程序立即解决了问题,但是在你的解决方案中的代码却没有。 - Bibberty
@VLAZ 有趣,我从未见过它们被使用。也许我应该多出去一些;-) - jarmod
1
@Bibberty res 接收一个 Promise,因此整个结果将等待该 Promise 首先解决。如果结果是另一个 Promise,则 Promise 会自动展平/合并。 - VLAZ
显示剩余3条评论
1个回答

1

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

你目前正在使用内部承诺立即解决外部承诺,但该内部承诺并未返回任何内容,因此是undefined。直接返回该承诺即可,更加简洁明了。


啊!我知道它是个简单的东西。我立刻意识到了这一点,然后解决了内部问题,但我认为你的更清晰,所以会重构成那样,谢谢! - Red Baron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接