firebase realtime database once vs on?

女生的网名这么多〃 提交于 2020-01-22 03:45:07

问题


Im using firebase realtime database on node js like database for API.

What's the different between once() and on()?

My code with once() work very slowly.

What is it needed for off()?

Example

router.get('/:qrid', async(req, res)=>{
    let id = req.params.qrid;
    let ref = firebase.database().ref('/qr/'+id);
    let snapshot = await ref.once('value');
    res.json(Object.assign({}, snapshot.val()));
});

This work very slowly (250ms-3000ms). When I use on() it all faster.

router.get('/:qrid',(req, res)=>{
    let id = req.params.qrid;
    let ref = firebase.database().ref('/qr/'+id);
    ref.on('value',(snapshot) => res.json(Object.assign({}, snapshot.val())));
});

回答1:


From the docs:

once:

once(eventType: EventType, successCallback?: function, failureCallbackOrContext?: function | Object | null, context?: Object | null): Promise<DataSnapshot>

Listens for exactly one event of the specified event type, and then stops listening.

This is equivalent to calling on(), and then calling off() inside the callback function. See on() for details on the event types.

on:

on(eventType: EventType, callback: function, cancelCallbackOrContext?: Object | null, context?: Object | null): function

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Use off( ) to stop receiving updates.

off() is used to detach a callback previously attached with on()

You can check the reference:

https://firebase.google.com/docs/reference/js/firebase.database.Reference.html



来源:https://stackoverflow.com/questions/59210946/firebase-realtime-database-once-vs-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!