Firebase返回onSnapshot

Firebase返回onSnapshot

本文介绍了Firebase返回onSnapshot许诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用firebase/firestore,并且正在寻找一种返回快照承诺的方法.

I'm using firebase/firestore and I'm looking a way to return promise of snapshot.

onlineUsers(){
     // i want to return onSnapshot
    return this.status_database_ref.where('state','==','online').onSnapshot();
}

在我做过的其他文件中

  componentDidMount(){
    // this.unsubscribe = this.ref.where('state','==','online').onSnapshot(this.onCollectionUpdate)
    firebaseService.onlineUsers().then(e=>{
        console.log(e)
    })
}

我得到了错误

TypeError:_firebaseService2.default.unsubscribe不是函数

TypeError: _firebaseService2.default.unsubscribe is not a function

如果我这样做

onlineUsers(){
   return  this.status_database_ref.where('state','==','online').onSnapshot((querySnapshot)=>{
        return querySnapshot
    })
}

我知道

TypeError: _firebaseService2.default.onlineUsers(...).then is not a function

此外,当我这样做的时候

in addition,when I do this way

   this.unsubscribe = firebaseService.onlineUsers().then((querySnapshot)=>{
        console.log(querySnapshot.size)
        this.setState({count:querySnapshot.size})
    })

//其他文件

 onlineUsers(callback) {
    return this.status_database_ref.where('state', '==', 'online').get()
}

它不收听Firebase的更改,这意味着如果我更改了Firebase,则不会更新或更改大小.

it not listen to change into firebase, means if I change in firebase it's not update or change the size..

----消防站功能-我试图使firestore函数在每次UserStatus节点更新时触发,但这需要花几秒钟,而且对我来说很慢.

---- firestore function ---I tried to make firestore function that trigger each time the UserStatus node updated but this take some seconds and it slow for me.

module.exports.onUserStatusChanged = functions.database
.ref('/UserStatus/{uid}').onUpdate((change, context) => {
    // Get the data written to Realtime Database
    const eventStatus = change.after.val();

    // Then use other event data to create a reference to the
    // corresponding Firestore document.
    const userStatusFirestoreRef = firestore.doc(`UserStatus/${context.params.uid}`);


    // It is likely that the Realtime Database change that triggered
    // this event has already been overwritten by a fast change in
    // online / offline status, so we'll re-read the current data
    // and compare the timestamps.
    return change.after.ref.once("value").then((statusSnapshot) => {
        return statusSnapshot.val();
    }).then((status) => {
        console.log(status, eventStatus);
        // If the current timestamp for this data is newer than
        // the data that triggered this event, we exit this function.
        if (status.last_changed > eventStatus.last_changed) return status;

        // Otherwise, we convert the last_changed field to a Date
        eventStatus.last_changed = new Date(eventStatus.last_changed);

        // ... and write it to Firestore.
        //return userStatusFirestoreRef.set(eventStatus);
        return userStatusFirestoreRef.update(eventStatus);
    });
});

计算和更新在线用户数的功能

function to calculate and update count of online users

module.exports.countOnlineUsers = functions.firestore.document('/UserStatus/{uid}').onWrite((change, context) => {

    const userOnlineCounterRef = firestore.doc('Counters/onlineUsersCounter');

    const docRef = firestore.collection('UserStatus').where('state', '==', 'online').get().then(e => {
        let count = e.size;
        return userOnlineCounterRef.update({ count })
    })
})

推荐答案

JavaScript中的 Promise 只能解析(或拒绝)一次.另一方面, onSnapshot 可以给出多次结果.这就是 onSnapshot 不返回承诺的原因.

A Promise in JavaScript can resolve (or reject) exactly once. A onSnapshot on the other hand can give results multiple times. That's why onSnapshot doesn't return a promise.

在您当前的代码中,您剩下一个悬挂在 status_database_ref 上的侦听器.由于您对数据不做任何事情,因此继续监听很浪费.

In your current code, you're left with a dangling listener to status_database_ref. Since you don't do anything with the data, it is wasteful to keep listening for it.

使用 get :

onlineUsers(callback){
    this.status_database_ref.where('state','==','online').get((querySnapshot)=>{
        callback(querySnapshot.size)
    })
}

或者按照您的原始方法:

Or in your original approach:

onlineUsers(){
    return this.status_database_ref.where('state','==','online').get();
}

这篇关于Firebase返回onSnapshot许诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:53