我正在我的angular / firebase项目中处理数据库事务。我有这个:
const transactionResult = await db.runTransaction(async trans => {
// Get references:
const parentGroupRef = db.collection('Groups').doc(parentGroupID);
const childGroupRef = db.collection('Groups').doc(childGroupID);
// Get documents:
const promiseArray: Promise<any>[] = [];
promiseArray.push(trans.get(parentGroupRef));
promiseArray.push(trans.get(childGroupRef));
const promiseResults: any[] = await Promise.all(promiseArray);
// Get the group documents of the promise results:
const parentGroupDoc = promiseResults.filter(groupDoc => { return groupDoc.id === parentGroupID; })[0];
const childGroupDoc = promiseResults.filter(groupDoc => { return groupDoc.id === childGroupID; })[0];
// Get data:
if (parentGroupDoc && parentGroupDoc.exists && childGroupDoc && childGroupDoc.exists) {
const parentGroupData = parentGroupDoc.data();
const childGroupData = childGroupDoc.data();
// Add child to parent and visa-versa:
const results: any[] = [];
if (parentGroupData.childGroupIDs.indexOf(childGroupID) === -1) {
parentGroupData.childGroupIDs.push(childGroupID);
const addChildResult = trans.set(parentGroupRef, parentGroupData, {merge: true});
results.push(addChildResult);
}
if (childGroupData.parentGroupIDs.indexOf(parentGroupID) === -1) {
childGroupData.parentGroupIDs.push(parentGroupID);
const addParentResult = trans.set(childGroupRef, childGroupData, {merge: true});
results.push(addParentResult);
}
if (results.length > 0) {
return await Promise.all(results);
} else {
return Promise.reject('No changes made');
}
} else {
console.log('Could not find parent or child group, or both.');
return Promise.reject('Could not find parent or child group, or both.');
}
});
如您所见,我正在等待从trans.get(...)返回的承诺。对trans.set(...)进行相同的设置有意义吗?对于trans.get(…)这样做是有意义的,因为trans.get(…)返回一个promise。但是trans.set(…)返回一个事务对象。所以我的问题是:trans.set(...)是否同步?