When a push event happens it will return back a new key.
For example from the 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();
What I'm trying to do:
Now I want to use this key directly after in order to effect change in another part of the database.
But because of the asynchronous nature of JavaScript I've been getting tripped up.
I've tried the success callback:
var newMessageIDRef = firebaseMessagesRef.push({
authorName: 'Nick',
text:"Hello!"
},printKey(newMessageIDRef));
var printKey = function(newMessageIDRef) {
console.log(newMessageIDRef);//undefined
}
(I assume that printKey
is being called before newMessageIDRef is set)
I've tried using "then":
var newMessageIDRef = firebaseConvosRef.push({
authorName: 'Nick',
text:"Hello!",
}).then(printKey(newMessageIDRef));
var printKey = function(newMessageIDRef) {
console.log(newMessageIDRef);//undefined
}
(I assume the parens is causing printKey
to be immediately executed, which makes me wonder how I add params but not cause early execution)
Question:
Is there some conventional way to handle something so common or is my best solution to use a Promise
and handle the key with resolve
?
Update(not answered yet though):
Below is working but it doesn't make sense.
var printKey = function(newMessageIDRef) {
console.log(newMessageIDRef);//undefined
}
var newMessageIDRef = firebaseConvosRef.push({
authorName: 'Nick',
text:"Hello!",
});
printKey(newMessageIDRef)
I would think that newMessageIDRef
would not necessarily be returned by the time printKey
was called.