2017-03-17 43 views
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); 
} 

回答

2

push()方法(當不帶任何參數調用,因爲它是在你從火力地堡文檔共享的例子)是一個客戶端的操作。不需要往返服務器,因爲它會生成統計保證在客戶端中唯一的密鑰。

+0

TY。非常好知道。這種方式更容易。 –