ren*_*dom 7 javascript firebase google-cloud-firestore
我正在尝试使用async/await与事务.但是获取错误"Argument"updateFunction"不是一个有效的函数."
var docRef = admin.firestore().collection("docs").doc(docId);
let transaction = admin.firestore().runTransaction();
let doc = await transaction.get(docRef);
if (!doc.exists) {throw ("doc not found");}
var newLikes = doc.data().likes + 1;
await transaction.update(docRef, { likes: newLikes });
Run Code Online (Sandbox Code Playgroud)
小智 13
上述内容对我不起作用并导致此错误:"[错误:还必须写入事务中读取的每个文档.".
下面的代码使用async/await并且工作正常.
try{
await db.runTransaction(async transaction => {
const doc = await transaction.get(ref);
if(!doc.exists){
throw "Document does not exist";
}
const newCount = doc.data().count + 1;
transaction.update(ref, {
count: newCount,
});
})
} catch(e){
console.log('transaction failed', e);
}
Run Code Online (Sandbox Code Playgroud)
如果您查看文档,您会发现传递给runTransaction的函数是一个返回承诺(结果transaction.get().then())的函数。由于异步函数只是一个返回承诺的函数,因此您不妨编写db.runTransaction(async transaction => {})
如果您想从事务中传递数据,您只需要从这个函数返回一些东西。例如,如果您只执行更新,则不会返回任何内容。另请注意,更新函数返回事务本身,以便您可以链接它们:
try {
await db.runTransaction(async transaction => {
transaction
.update(
db.collection("col1").doc(id1),
dataFor1
)
.update(
db.collection("col2").doc(id2),
dataFor2
);
});
} catch (err) {
throw new Error(`Failed transaction: ${err.message}`);
}
Run Code Online (Sandbox Code Playgroud)
重要提示:正如一些用户所指出的,该解决方案没有正确使用事务。它只是使用事务获取文档,但更新在事务之外运行。
检查阿尔斯基的答案。/sf/answers/3671698201/
查看文档,runTransaction 必须接收 updateFunction 函数作为参数。(https://firebase.google.com/docs/reference/js/firebase.firestore.Firestore#runTransaction)
尝试这个
var docRef = admin.firestore().collection("docs").doc(docId);
let doc = await admin.firestore().runTransaction(t => t.get(docRef));
if (!doc.exists) {throw ("doc not found");}
var newLikes = doc.data().likes + 1;
await doc.ref.update({ likes: newLikes });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3733 次 |
| 最近记录: |