【发布时间】:2021-07-29 05:43:00
【问题描述】:
我正在尝试在 firestore 文档中为每个用户保存不同数量的值(相同类型)。这是使用数组完成的。
当用户决定添加一个新值时,我对需要完成的三个操作中的每一个都有一个函数。
- 从数据库中获取当前数组并赋值给一个变量
- 使用 push() 将用户输入添加到数组中
- 替换数据库中的旧数组
//gets arr from database
function get() {
console.log(arr);
firebase
.firestore()
.collection("test")
.doc("testArray")
.get()
.then((doc) => {
setArr(doc.data().arr);
})
.then(() => {
console.log(arr);
console.log("value retrieved");
});
}
//adds new object to arr
function add() {
arr.push({
a: 89,
b: 34,
});
console.log("value added");
console.log(arr);
}
//adds arr to database
function updateArray() {
firebase
.firestore()
.collection("test")
.doc("testArray")
.set({
arr: arr,
})
.then(() => {
console.log("array updated");
});
}
我的目标是使用一个函数来运行所有这些操作,这样一键即可完成。
我对异步 js 不是很熟悉,但我已经设法使用 async/await 让前两个函数按顺序运行。
//gets arr from database
async function get() {
console.log(arr);
await firebase
.firestore()
.collection("test")
.doc("testArray")
.get()
.then((doc) => {
setArr(doc.data().arr);
})
.then(() => {
console.log(arr);
console.log("value retrieved");
});
add();
}
async function call() {
await get();
updateArray();
}
但是第三个函数似乎仍然先运行,导致在添加新数据之前将数据库中的数据替换为空数组。
【问题讨论】:
标签: javascript firebase react-native asynchronous google-cloud-firestore