gpt4 book ai didi

javascript - Firebase:异步/等待事务

转载 作者:数据小太阳 更新时间:2023-10-29 05:51:16 25 4
gpt4 key购买 nike

我正在尝试对事务使用异步/等待。但是出现错误“参数“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 });

最佳答案

以上对我不起作用并导致此错误:“[错误:事务中读取的每个文档也必须写入。]”。

下面的代码使用了 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);
}

关于javascript - Firebase:异步/等待事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49644614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com