Firestore 查询有时不包含更新的数据
Firestore query sometimes doesn't contain updated data
我正在使用 firestore 的节点 sdk。在我的代码中,我调用了 function1,它更新了 firestore 中的 table。当该函数结束时,我调用 function2,它运行查询以获取 table 的引用。大约 80% 的时间它都可以工作,但有时我需要的数据(在 function1 中添加到文档中)不会在快照中返回,因此会引发错误。
我在更新之前添加了一个 await 关键字,但这似乎并没有让代码等待 firestore 更新完成。
我想我也可以 return 我要在 function1 中更新的数据并将其传递给 function2,但这感觉有点老套,不过我想我会省点钱,因为我不会不必再获取 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()
以上代码没有异步问题。我的代码的另一部分有一个不同的异步问题,这导致了我的问题。
我正在使用 firestore 的节点 sdk。在我的代码中,我调用了 function1,它更新了 firestore 中的 table。当该函数结束时,我调用 function2,它运行查询以获取 table 的引用。大约 80% 的时间它都可以工作,但有时我需要的数据(在 function1 中添加到文档中)不会在快照中返回,因此会引发错误。
我在更新之前添加了一个 await 关键字,但这似乎并没有让代码等待 firestore 更新完成。
我想我也可以 return 我要在 function1 中更新的数据并将其传递给 function2,但这感觉有点老套,不过我想我会省点钱,因为我不会不必再获取 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()
以上代码没有异步问题。我的代码的另一部分有一个不同的异步问题,这导致了我的问题。