Firebase.ServerValue.TIMESTAMP 在侦听器和实际添加数据的客户端之间未同步

时间:2023-03-17
本文介绍了Firebase.ServerValue.TIMESTAMP 在侦听器和实际添加数据的客户端之间未同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这是最简单的例子:

var fb = new Firebase('https://xxxxxxxxxxx.firebaseio.com/test');

fb.limitToLast(1).on('child_added', function(snap) {
    console.log('key', snap.key());
    console.log('val', snap.val());
});

fb.push({
    date_now: Firebase.ServerValue.TIMESTAMP
});

如果我使用此脚本打开两个选项卡,实际推送数据的选项卡会在 child_added 回调中获得 local 时间戳,而另一个仅侦听的选项卡会获得适当的服务器生成的选项卡.据我了解,这样做是为了排除往返并节省带宽.

If I open two tabs with this script, the one that actually pushes data gets local timestamp in child_added callback and the other tab that just listens gets proper server-generated one. As far as I understand it's done to exclude round-trip and save bandwidth.

但对于我的任务,这种行为是不可接受的.我该如何克服它?

But for my task this behaviour is unacceptable. How can I overcome it?

这是来自 pusher 的 console.log:

This is the console.log from pusher:

key -K59mrvEUhTaoNIQQoA4
val Object {date_now: 1449732570832}

和监听器(等于仪表板中看到的服务器数据):

and listeners (equals to server data seen in dashboard):

key -K59mrvEUhTaoNIQQoA4
val Object {date_now: 1449732571759}

推荐答案

Firebase 为该写入操作触发两个本地事件:

Firebase fires two local events for that write operation:

  1. 它会立即触发带有本地时间戳的 child_added 事件(已根据您对服务器的预期偏移进行更正)
  2. 它稍后会触发 child_changed 事件,其中包含服务器指定的实际时间戳.
  1. it immediately fires a child_added event with the local timestamp (corrected for your expected offset to the server)
  2. it later fires a child_changed event with the actual timestamp as the server specified it.

所以你可以通过监听这两个事件来解决问题:

So you can solve the problem by listening for both events:

var fb = new Firebase('https://xxxxxxxxxxx.firebaseio.com/test');

var query = fb.limitToLast(1);
query.on('child_added', function(snap) {
    console.log('key', snap.key());
    console.log('val', snap.val());
});
query.on('child_changed', function(snap) {
    console.log('key', snap.key());
    console.log('val', snap.val());
});

fb.push({
    date_now: Firebase.ServerValue.TIMESTAMP
});

一般建议处理所有 child_* 事件,而不仅仅是 child_added.服务器必须更新或删除该值以更正本地事件可能还有更多原因.

In general it is recommended to handle all child_* events and not just child_added. There may be more reasons why the server has to update or remove the value, to correct for the local event.

如果您更喜欢使用单个回调/事件处理程序,您还可以侦听 value 事件:

If you prefer having a single callback/event handler, you can also listen for the value event:

var query = fb.limitToLast(1);
query.on('value', function(snap) {
    snap.forEach(function(child) {
        console.log('key', child.key());
        console.log('val', child.val());
    });
});

您会注意到回调中 forEach() 的使用.

You'll note the use of forEach() in the callback.

这篇关于Firebase.ServerValue.TIMESTAMP 在侦听器和实际添加数据的客户端之间未同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Javascript时间戳编号不是唯一的 下一篇:Javascript - 将日期字符串重新格式化为 ISO8601

相关文章