我正在使用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);
});
});
});
答案 0 :(得分:2)
只要您有这样的多种操作,解决方案就是使用Promise.all()
。这需要一组诺言,然后返回一个诺言,当您传递的所有诺言都得到解决时,该诺言就会解决。
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();
var p1 = db.doc('Utils/lastPost').update({timestamp: timestamp});
var p1 = db.runTransaction(t => {
return t.get(mayorRef).then(snapshot => {
var new_budget = snapshot.data().b - 100;
return t.update(mayorRef, {b: new_budget});
})
});
return Promise.all([p1, p2]);
});