【发布时间】:2020-07-15 23:54:54
【问题描述】:
我正在使用 firestore 的 node sdk。在我的代码中,我调用了 function1,它更新了 firestore 中的一个表。当该函数结束时,我调用 function2,它运行查询以获取表的引用。大约 80% 的时间它可以工作,但有时我需要的数据(在 function1 中添加到文档中)不会在快照中返回,因此会引发错误。
我在更新之前添加了一个 await 关键字,但这似乎并没有让代码等待 firestore 更新完成。
我想我也可以在 function1 中返回我要更新的数据并将其传递给 function2,但这感觉有点 hacky,虽然我想我会节省一点钱,因为我不必得到 1文件了。我也可以把它变成一个大函数,但这会变成一个 100 行函数。
这是我的代码的缩写版本:
const function1 = async (tableId) => {
const firestore = admin.firestore();
const tableSnapshot = await firestore.collection('tables').doc(tableId).get();
await tableSnapshot.ref.update({ smallBlind: {seat: 1, amount: 5000} }) // the seat number and amount number wont always be 1 and 5000. Otherwise I wouldn't need to look it up in function2
}
const function2 = async (tableId) => {
const firestore = admin.firestore();
const tableSnapshot = await firestore.collection('tables').doc(tableId).get();
const tableData = tableSnapshot.data();
const smallBlind = tableSnapshot.data().smallBlind; // the smallBlind data is not there. so smallBlind is undefined
}
const startStuff = async () => {
await function1(42); // example tableId is passed in
await function2(42);
}
startStuff()
【问题讨论】:
-
如果您在代码中采用
promise.then()方法,是否也会发生这种情况? -
@ralemos 我还没有尝试过,但由于 async/await 是 promise 的语法糖,我不明白为什么这很重要。
-
你是对的,我建议因为这似乎是一个同步问题,使用这种方法进行故障排除会更容易。
标签: node.js firebase google-cloud-firestore firebase-admin