Reputation: 561
I am using Firebase Cloud Functions, which get triggered by the creation of a document in Firestore. On creation of the object, I need to undertake two different operations in parallel:
So my questions are:
Here is my current code:
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);
});
});
});
Upvotes: 0
Views: 91
Reputation: 598817
Whenever you have multiple operations like this, the solution is to use Promise.all()
. This takes an array of promises, and in turn returns a promise that resolves when all promises you passed in are resolved.
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]);
});
Upvotes: 2