Firebase delay when retrieving data

2019-08-17 23:05发布

Using the Firebase API to read data from the database gives me an awkward moment of things just suddenly coming to place 1-2 seconds after web UI has loaded. Does anyone have any alternatives to reading data? I've tried REST API, but i still need to use the Firebase authlistener, which again gives me a delay before i can retrieve user id and use the REST API. It doesn't matter how small the data I'm reading is.

I would appreciate anything over a loading screen!

1条回答
Bombasti
2楼-- · 2019-08-17 23:44

below is a simple example to fetch the user status on firebase

const app = firebase.initializeApp()
const db = app.database();
let unsub;

const user = new Promise((resolve, reject) => {

    unsub = app.onAuthStateChanged(
        status => {

            if ( status === null ) {

                resolve(app.signInWithEmailAndPassword());

            } else resolve(user);

        },
        err => reject(err);
    )


});


user.then(unsub, unsub);

db.ref("path/to/data").on("child_added", () => {});

// this promise will fail if the user is not
// auth
const data = db.ref("path/to/data").once("value");

You don't have to wait for this promise to be settled to open subscription. However depending of your app's settings your database cannot be read if you are not authenticated.

So a solution can be pretty straighforward.

With a little bit of refactor we have :

const getData = () => db.ref("path/to/data").once("value");

user.then(getData).then(data => { /* data here */ });

This last promise will effectively be resolved as soon as the user is auth once if and only if everything went ok. You can open the subscription before authenticating the user but it is not guarenteed to go faster. The only way to beat it is by simply removing the reading rights needed to access the db in the first place...

查看更多
登录 后发表回答