gpt4 book ai didi

firebase - 交易中的数据为空

转载 作者:行者123 更新时间:2023-11-30 11:50:04 25 4
gpt4 key购买 nike

我在交易方面遇到问题。事务中的数据始终为空,并且更新处理程序仅被调用一次。 documentation说:

To accomplish this, you pass transaction() an update function which is used to transform the current value into a new value. If another client writes to the location before your new value is successfully written, your update function will be called again with the new current value, and the write will be retried. This will happen repeatedly until your write succeeds without conflict or you abort the transaction by not returning a value from your update function

现在我知道现在没有其他客户端访问该位置。其次,如果我正确阅读了文档,则 updateCounters 函数如果无法检索和更新数据,则应多次调用。

另一件事 - 如果我取出条件 if (counters === null) 执行将失败,因为 counters 为 null 但在随后的尝试中事务完成得很好 - 检索数据并进行更新。

在此位置上进行简单的一次设置即可正常工作,但并不安全。

请问我错过了什么?

这是代码

self.myRef.child('counters')
.transaction(function updateCounters(counters){
if (counters === null) {
return;
}
else {
console.log('in transaction counters:', counters);
counters.comments = counters.comments + 1;
return counters;
}
}, function(error, committed, ss){
if (error) {
console.log('transaction aborted');
// TODO error handling
} else if (!committed){
console.log('counters are null - why?');
} else {
console.log('counter increased',ss.val());
}
}, true);

这是该位置的数据

counters:{
comments: 1,
alerts: 3,
...
}

最佳答案

通过在 if( ... === null ) block 中返回 undefined,您将中止事务。因此,它永远不会向服务器发送尝试,永远不会意识到本地缓存的值与远程的不同,并且永远不会使用更新的值(来自服务器的实际值)重试。

这一点可以通过以下事实得到证实:commitedfalse 并且成功函数中的错误为 null(如果交易是这样的话,就会发生这种情况)已中止。

交易的工作原理如下:

  • 将本地缓存的值传递到处理函数中,如果您从未从服务器获取过此数据,则本地缓存的值为null(该路径最有可能的远程值)<
  • 从处理函数获取返回值,如果该值为未定义,则中止事务,否则,创建当前值(null)的哈希值并传递该值和新值(由处理函数)到服务器
  • 如果本地哈希与服务器当前的哈希相匹配,则应用更改并且服务器返回成功结果
  • 如果服务器事务未应用,服务器返回新值,然后客户端使用服务器更新后的值再次调用处理函数,直到成功
  • 当最终成功,并且发生不可恢复的错误,或者事务被中止(通过从处理函数返回 undefined)时,将使用结果调用 success 方法。

因此,为了使这项工作正常进行,显然您不能在第一个返回值上中止事务。

实现相同结果的一种解决方法(尽管它是耦合的,并且不如仅使用设计的事务那么高效或合适)是将事务包装在 once('value', .. .) 回调,这将确保在运行事务之前将其缓存在本地。

关于firebase - 交易中的数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com