Firestore transaction - Transaction failed: TypeError: transaction.set(...).then is not a function
Firestore transaction - Transaction failed: TypeError: transaction.set(...).then is not a function
我已经编写了一个事务来在尝试创建用户之前检查 Firestore 中是否存在该用户。
setUserData(uid, email, displayName, photoURL, firstName, lastName, referralId) {
const userRef = this.afs.firestore.collection('users').doc(`${uid}`);
return this.afs.firestore.runTransaction(async (transaction: any) => {
const doc = await transaction.get(userRef);
let userData = {};
if (!doc.exists) {
userData = {
uid: uid,
email: email,
displayName: displayName,
photoURL: photoURL,
emailVerified: true,
firstName: firstName,
lastName: lastName,
referralId: referralId
};
transaction.set(userRef, { userData }, { merge: true }).then(() => {
this.referralService.addUserToWaitlist(referralId);
});
}
}).then(() => {
if (!environment.production) {
console.log(
'Transaction successfully committed.'
);
}
}).catch((error) => {
if (!environment.production) {
console.log('Transaction failed: ', error);
}
});
}
但是,我不断收到以下错误:
Transaction failed: TypeError: transaction.set(...).then is not a function
transaction
没有 then
的等价物吗?
这不是在交易中编写文档的方式。由于交易是一个全有或全无的操作,你不能等到 set()
完成再继续另一个交易,所以它对 return 一个承诺没有帮助.对于事务,您必须在函数结束之前 set()
所有文档,然后在最后,事务将尝试将它们全部写入。如果不能全部原子写,你的交易函数又会运行
另请注意,transaction.set() 的普通 JavaScript API(不是 Angular)被声明为 return 相同的事务对象而不是承诺.
我已经编写了一个事务来在尝试创建用户之前检查 Firestore 中是否存在该用户。
setUserData(uid, email, displayName, photoURL, firstName, lastName, referralId) {
const userRef = this.afs.firestore.collection('users').doc(`${uid}`);
return this.afs.firestore.runTransaction(async (transaction: any) => {
const doc = await transaction.get(userRef);
let userData = {};
if (!doc.exists) {
userData = {
uid: uid,
email: email,
displayName: displayName,
photoURL: photoURL,
emailVerified: true,
firstName: firstName,
lastName: lastName,
referralId: referralId
};
transaction.set(userRef, { userData }, { merge: true }).then(() => {
this.referralService.addUserToWaitlist(referralId);
});
}
}).then(() => {
if (!environment.production) {
console.log(
'Transaction successfully committed.'
);
}
}).catch((error) => {
if (!environment.production) {
console.log('Transaction failed: ', error);
}
});
}
但是,我不断收到以下错误:
Transaction failed: TypeError: transaction.set(...).then is not a function
transaction
没有 then
的等价物吗?
这不是在交易中编写文档的方式。由于交易是一个全有或全无的操作,你不能等到 set()
完成再继续另一个交易,所以它对 return 一个承诺没有帮助.对于事务,您必须在函数结束之前 set()
所有文档,然后在最后,事务将尝试将它们全部写入。如果不能全部原子写,你的交易函数又会运行
另请注意,transaction.set() 的普通 JavaScript API(不是 Angular)被声明为 return 相同的事务对象而不是承诺.