Firebase,异步检索数据 [英] Firebase, retrieving data asynchronously

查看:56
本文介绍了Firebase,异步检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Javascript编写了一个Promise,以延迟动画,直到从我的Firebase数据库中检索到某些数据为止.问题是由于某种原因,promise无法正常工作,并且代码无法异步运行.我没有正确使用此承诺,还是有其他问题?

I wrote a promise in javascript to delay an animation until some data is retrieved from my firebase database. The problem is that for some reason the promise isn't working, and the code isn't running asynchronously. Am i not using this promise properly, or is there another issue?

var name = document.querySelector('.name')

new Promise (function() {
        firebase.database().ref('users/' + userId ).on('value', function(snap) {
            console.log('first');   
            name.innerText = snap.child('name').val();
        });
    }).then(console.log('second'));

我的问题是,当我检查控制台时,我发现代码不是异步运行的,并且我会看到消息以错误的顺序记录消息,即第二"然后第一".

My issue is that when I check the console, I find that the code isn't running asynchronously, and I will see the messages logged in the wrong order, 'second' then 'first'.

推荐答案

第一个问题是(正如我对Cartant的回答所述), on()处理程序可以被多次调用,因此不能被视为诺言.

The first problem is that (as I commented on cartant's answer) an on() handler can be invoked multiple times and thus cannot be treated as a promise.

如果只关心节点的当前值,则可以使用 once(),它会返回一个Promise:

If you only care about the current value of the node, you can use once(), which does return a promise:

var name = document.querySelector('.name')

firebase.database().ref('users/' + userId ).once('value', function(snap) {
    console.log('first');   
    name.innerText = snap.child('name').val();
}).then(function() { console.log('second') });

或者,如果您也关心值的更改,则可能要继续使用 on().但是在这种情况下,您应该传递回调.

Alternatively, if you do care about changes in the value too, you may want to keep on using on(). But in that case you should pass in a callback.

var name = document.querySelector('.name')

firebase.database().ref('users/' + userId ).on('value', function(snap) {
    console.log('first');   
    name.innerText = snap.child('name').val();
});

如果要显式检测其中的第一个值,请执行以下操作:

If you want to explicitly detect the first value in this, do something like:

var name = document.querySelector('.name'),
    isFirst = true;

firebase.database().ref('users/' + userId ).on('value', function(snap) {
    console.log('first');   
    name.innerText = snap.child('name').val();
    if (isFirst) {
        console.log('second');
    }
    isFirst = false;
});

这篇关于Firebase,异步检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆