簡體   English   中英

使用 Firebase 參考的最佳做法

[英]Best practice for using Firebase Reference

調用下面的函數來創建一個帖子

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

這是該函數的另一個版本

const postRef = app.database().ref('posts');
const createPost = (newPost) => {
 postRef.push(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);
}

至於你原來的問題,如果只使用一次,你不應該聲明一個變量,所以我會選擇第一個變體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM