0
我注意到該示例使用.push
方法但中的newPostKey,而不是嵌套在.then
中,且沒有回調。在posted example中,.update
如何知道要等待解決該newPostKey的承諾? .update
知道一個變量是一個承諾嗎?換句話說,我是這樣做的。而他們這樣做如下:Firebase更新方法官方示例/ push().key作爲變量
var postData = {
"name": supplyNameInput.value,
"description": supplyDescriptionInput.value,
"type": doc.querySelector('input[name = "supply-type"]:checked').value,
"imageURL": clock.now,
"last modified": clock.now,
"author": uid
};
var newSupply = suppliesRef.push(postData, function(error) {
if (error){
//error
} else {
//succesfull
}
}).then((snap) => {
suppliesRef.child(snap.key).once('value').then(function(snapshot) {
// The Promise was fulfilled
console.log(snap.key);
//Now I have generated newKey as snap.key
}, function(error) {
// The Promise was rejected.
console.error(error);
});
});
官方示例。
function writeNewPost(uid, username, picture, title, body) { // A post entry. var postData = { author: username, uid: uid, body: body, title: title, starCount: 0, authorPic: picture }; // Get a key for a new Post. var newPostKey = firebase.database().ref().child('posts').push().key; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['/posts/' + newPostKey] = postData; updates['/user-posts/' + uid + '/' + newPostKey] = postData; return firebase.database().ref().update(updates); }
TY。非常好知道。這種方式更容易。 –