当推送事件发生时,它将返回一个新 key 。
例如来自Docs :
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
我正在尝试做什么:
现在我想直接使用此键来影响数据库其他部分的更改。
但是由于 JavaScript 的异步特性,我一直被绊倒。
我尝试过成功回调:
var newMessageIDRef = firebaseMessagesRef.push({
authorName: 'Nick',
text:"Hello!"
},printKey(newMessageIDRef));
var printKey = function(newMessageIDRef) {
console.log(newMessageIDRef);//undefined
}
(我假设在设置 newMessageIDRef 之前调用 printKey
)
我尝试过使用“then”:
var newMessageIDRef = firebaseConvosRef.push({
authorName: 'Nick',
text:"Hello!",
}).then(printKey(newMessageIDRef));
var printKey = function(newMessageIDRef) {
console.log(newMessageIDRef);//undefined
}
(我假设括号导致 printKey
立即执行,这让我想知道如何添加参数但不会导致提前执行)
问题:
是否有一些传统的方法来处理如此常见的问题,或者是我使用 Promise
并使用 resolve
处理 key 的最佳解决方案?
更新(尚未答复):
下面可以工作,但没有意义。
var printKey = function(newMessageIDRef) {
console.log(newMessageIDRef);//undefined
}
var newMessageIDRef = firebaseConvosRef.push({
authorName: 'Nick',
text:"Hello!",
});
printKey(newMessageIDRef)
我认为 newMessageIDRef
不一定会在调用 printKey
时返回。
最佳答案
Firebase JavaScript SDK 不公开任何 promise ,因此没有 then()
。相反,它基于回调来工作。
除此之外,我不完全确定您想要完成什么。因此,我只提供一些常见的片段,希望其中之一能有所帮助。
Firebase 的 push()
操作是纯客户端操作。它不会执行与服务器的往返,而是在客户端上生成统计上唯一的 ID。
现在假设您要创建一个新帖子(在 /posts/$postid
下)并将该新帖子的链接添加到数据库的另一个位置(例如/users/$uid/posts/$postid
):
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
// ref is a reference to the root, uid is the id of the current user
var userRef = ref.child('users').child(uid);
// Write the post to Firebase
newPostRef.set({ title: 'Firebase: Using the newly created key...', uid: uid }, function(newRef) {
userRef.child('posts').child(postID).set(true);
});
您会注意到,我没有在回调中使用 newRef
。因为我已经知道 postID
是什么。
上述方法将对 Firebase 执行两次写入操作:
- 实际帖子
- 用户个人资料中帖子的链接
自 Firebase 2.4(适用于 JavaScript,2.3 适用于 Android 和 iOS)起,可以将这两种写入作为单个操作执行。这再次利用了我们可以“预先计算”post-ID 作为客户端 push()
操作的事实:
var ref = new Firebase('https://your-app.firebaseio.com');
var postsRef = ref.child('posts');
// Get a unique ID generated by push()
var postID = postsRef.push().key();
// Create a single object, where we'll put all updates
var updates = {};
// We'll put the post into /posts/$postId
updates['/posts/'+postID] = { title: 'Firebase: Using the newly created key...', uid: uid };
// Put the postId under /users/$uid/posts/$postId
updates['/users/'+uid+'/posts/'+postID] = true;
// Now write to both locations in one "big" swoop:
ref.update(updates);
了解更多相关信息:
关于javascript - Firebase:在成功回调中使用新创建的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561969/