我正在使用 Firebase 和 Javascript。我需要获取由 push()
创建的引用的 key 。
我的代码等待推送返回的 promise ,然后读取 key 。它看起来像这样:
firebase.database().ref("preds/").push()
.then(function(newReference){
console.log(newReference.key);
});
现在我正在查看同事编写的一段代码。它不使用 promise 。相反,它直接使用 key :
var newReference = firebase.database().ref("preds/").push()
console.log(newReference.key)
这看起来确实好多了(特别是因为真实的代码比这些示例长)。但我怀疑这可能是一种竞争条件。如果我们仍在等待数据库的响应并且 key 已被使用怎么办? 但我无法用他的代码产生问题。
我查看了 Firebase docs ,而且它们有点令人困惑。
它说 push()
返回一个:
Combined Promise and Reference; resolves when write is complete, but can be used immediately as the Reference to the child location.
他们的示例如下所示:
var messageListRef = firebase.database().ref('message_list'); var newMessageRef = messageListRef.push(); newMessageRef.set({ 'user_id': 'ada', 'text': 'The Analytical Engine weaves algebraical patterns just as the Jacquard loom weaves flowers and leaves.' });
这看起来与 newReference.key
的使用类似,但它们都不是阻塞的。如果我理解正确的话,这些函数只是链接起来异步执行。
不过,他们确实表示可以立即使用该引用来访问子位置
。
我搜索了SO并发现了这个问题:In Firebase when using push() How do I pull the unique ID Dan_Mindru 说:
To anybody finding this question & using Firebase 3+, the way you get auto generated object unique ids after push is by using the key property (not method) on the promise snapshot
他的代码看起来就像我的初始版本:
firebase
.ref('item')
.push({...})
.then((snap) => {
const key = snap.key
})
我知道这是围绕 firebase 的一个非常常见的问题,但我希望我已经提供了足够的背景来证明我的困惑。 获取新创建的引用的 key 的正确方法是什么? 我必须等待 promise 还是可以直接访问 key ?
最佳答案
调用push()
时生成的 key 是纯客户端操作。当您调用不带参数的 push()
时,不会涉及对服务器的调用。因此,您共享的前两个代码片段是等效的。
在最后一个代码片段中,push({...})
确实调用服务器将对象写入数据库。但这里新子节点的 key 也是在客户端代码中生成的。
有关这些推送 ID 的更多信息,请参阅博客文章:The 2^120 Ways to Ensure Unique Identifiers .
关于javascript - firebase:获取ThenableReference的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52498500/