【发布时间】:2019-02-14 01:13:39
【问题描述】:
我正在使用 Firebase Cloud Functions,它通过在 Firestore 中创建文档来触发。在创建对象时,我需要并行执行两个不同的操作:
- 更新特定文档中的字段值(不是创建并触发云功能的文档)
- 在另一个文档上运行事务。
所以我的问题是:
- 如何确保我的两个操作都在结束云功能本身之前成功完成?
- 如何为这两个操作中的每一个实现单独的重试机制(因为我不希望整个函数有一个共同的重试机制,因为它可以重做事务操作,即使它是另一个操作失败)?
这是我当前的代码:
exports.onCityCreated = functions.firestore
.document('Cities/{cityId}')
.onCreate((snap, context) => {
const db = admin.firestore();
const newCity = snap.data();
const mayorId = newEvent.mayorID;
const mayorRef = db.doc('Users/'+ mayorId);
const timestamp = admin.firestore.FieldValue.serverTimestamp();
db.doc('Utils/lastPost').update({timestamp: timestamp}); //First Operation - Timestamp Update
return db.runTransaction(t => { //Second Operation - Transaction
return t.get(mayorRef).then(snapshot => {
var new_budget = snapshot.data().b - 100;
return t.update(mayorRef, {b: new_budget});
})
.then(result => {
return console.log('Transaction success!');
})
.catch(err => {
console.log('Transaction failure:', err);
});
});
});
【问题讨论】:
标签: javascript firebase asynchronous google-cloud-firestore google-cloud-functions