Javascript 如何确保云功能中的所有操作都已成功完成?
我使用的是Firebase云函数,它是在Firestore中创建文档时触发的。创建对象时,我需要并行执行两个不同的操作:Javascript 如何确保云功能中的所有操作都已成功完成?,javascript,firebase,asynchronous,google-cloud-firestore,google-cloud-functions,Javascript,Firebase,Asynchronous,Google Cloud Firestore,Google Cloud Functions,我使用的是Firebase云函数,它是在Firestore中创建文档时触发的。创建对象时,我需要并行执行两个不同的操作: 更新特定文档(不是创建并触发云功能的文档)中字段的值 在另一个文档上运行事务 所以我的问题是: 在结束云功能之前,如何确保我的两项操作都已成功完成 我如何为两个操作中的每个操作实施单独的重试机制(因为我不希望整个功能都有一个共同的重试机制,因为即使是另一个操作失败了,它也可以重做事务操作) 这是我目前的代码: exports.onCityCreated = functions
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);
});
});
});
每当您有多个这样的操作时,解决方法就是使用
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]);
});
每当您有多个这样的操作时,解决方法就是使用
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]);
});
谢谢它起作用了。现在,如果一个操作失败了,我怎么知道哪个操作失败了呢。如果两者都失败了呢?另外,我如何为它们中的每一个实现单独的重试机制?我不认为
Promise.all()
公开了足够的信息来确定哪些承诺失败了。看一看,谢谢。它起作用了。现在,如果一个操作失败了,我怎么知道哪个操作失败了呢。如果两者都失败了呢?另外,我如何为它们中的每一个实现单独的重试机制?我不认为Promise.all()
公开了足够的信息来确定哪些承诺失败了。看一看。