Javascript 使用Firebase参考的最佳实践

Javascript 使用Firebase参考的最佳实践,javascript,firebase,firebase-realtime-database,Javascript,Firebase,Firebase Realtime Database,调用下面的函数来创建帖子 constcreatepost=(newPost)=>{ app.database().ref('posts').push(newPost); } 这是该函数的另一个版本 const postRef=app.database().ref('posts'); const createPost=(newPost)=>{ 邮政参考推送(新邮政); } 哪一个更可取和为什么都将向数据库添加数据,但第二个更好: const postRef = app.database().r

调用下面的函数来创建帖子

constcreatepost=(newPost)=>{
app.database().ref('posts').push(newPost);
}
这是该函数的另一个版本

const postRef=app.database().ref('posts');
const createPost=(newPost)=>{
邮政参考推送(新邮政);
}

哪一个更可取为什么

都将向数据库添加数据,但第二个更好:

const postRef = app.database().ref('posts');
const createPost = (newPost) => {
 postRef.push(newPost);
}

因为
postRef
指的是数据库中的根节点,稍后您可能会在js文件中使用该节点

push返回一个承诺,该承诺在数据库写入完成时解析。如果您不等待它解决,您将不知道它是否失败,因为您的函数将成功返回。相反,您将收到未经处理的拒绝。此外,在函数返回后运行的任何东西在firebase中接收的CPU和内存都会减少。因此,将其改写如下:

const createPost = async (newPost) => {
    await app.database().ref('posts').push(newPost);
}

至于你最初的问题,如果只使用一次,你就不应该声明变量,所以我会选择第一个变量。

我怀疑,但我需要更多的细节来解释为什么这种方法的问题是,每当调用
createPost
函数时(可以多次)都会执行
app.database().ref('posts')
与变量
postRef
中包含的解析值相反,这并不重要。app.database().ref('posts')不使用您的后端。它是使用后端的推送方法