gpt4 book ai didi

javascript - Firebase更新方法官方示例/push().key作为变量

转载 作者:行者123 更新时间:2023-12-01 03:54:53 26 4
gpt4 key购买 nike

我注意到该示例使用 .push 方法 but 中的 newPostKey,而不是嵌套在 .then 中且没有回调。在 posted example.update 如何知道等待 Promise 解析 newPostKey? .update 知道变量是一个 promise 吗?换句话说,我像下面这样做。而他们的做法如下:

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);
}

最佳答案

push() 方法(在不带任何参数的情况下调用时,如您从 Firebase 文档中共享的示例中所示)是客户端操作。不需要往返服务器,因为它生成一个在统计上保证在客户端中唯一的 key 。

关于javascript - Firebase更新方法官方示例/push().key作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42847364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com