简体   繁体   English

我的异步 function 没有等待来自 Firebase 的 promise

[英]My async function is not waiting for a promise from Firebase

I am currently learning how async works, while working on a small project using Firebase databases.我目前正在学习异步的工作原理,同时使用 Firebase 数据库处理一个小项目。 As far as I understand await should pause the function until a promise is resolved, but in my case it's not waiting for that.据我了解 await 应该暂停 function 直到 promise 得到解决,但在我的情况下它不会等待。

I've shortened 2 functions I used to try and test this:我已经缩短了我用来尝试测试的 2 个函数:

async findUser(id) {
        await this.firebase.findUserData(id).then(
            value => {
                console.log('finduser stopped waiting');
                return value;
            }
        )
    }
async findUserData(userId){
        console.log('firebase started looking for user');
        firebase.database().ref('/users/' + userId).once('value').then(function(snapshot){
            let user = (snapshot.val());
            console.log('found: ' + user);
            return user;
        });
    }

The console output looks like this: (not allowed to embed images yet)控制台 output 看起来像这样:(还不允许嵌入图像)

It's running findUser first, followed by the Firebase call, but does not wait for that promise to complete before returning a value.它首先运行 findUser,然后是 Firebase 调用,但在返回值之前不会等待 promise 完成。 Found user id prints last.找到最后打印的用户 ID。

I'm sure I'm doing something really dumb here, but I couldn't figure it out for a while now and have nobody else to turn to.我确定我在这里做了一些非常愚蠢的事情,但我暂时无法弄清楚并且没有其他人可以求助。

Sorry if the question is poorly written.对不起,如果问题写得不好。 First time posting around here.第一次在这里发帖。 Welcome any feedback!欢迎任何反馈!

You should not mix await and then s.你不应该混合awaitthen s。 Then you also don't forget to await a promise (you never await / return the Promise returned by.once):然后,您也不要忘记等待 promise(您永远不会等待/返回由.once 返回的 Promise):

async findUserData(userId){
    console.log('firebase started looking for user');
    const snapshot = await firebase.database().ref('/users/' + userId).once('value');
    let user = (snapshot.val());
    console.log('found: ' + user);
    return user;
}

async findUser(id) {
    const value = await this.firebase.findUserData(id);
    console.log('finduser stopped waiting');
    return value;
}

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

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