2017-03-17 25 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。非常好知道。这种方式更容易。 –