如何避免使用firebase事务嵌套promise



在onDelete触发器中,我正在运行一个事务来更新一些对象。现在,在运行该事务之前,我需要进行一些清理并删除一些其他对象。在添加了清理代码后,我收到了一个关于嵌套承诺的警告,我不知道如何删除这些承诺。以下是一个片段:

exports.onDeleteAccount = functions.firestore
.document('accounts/{accountID}')
.onDelete((account, context) => {
// First do the cleanup and delete addresses of the account
const query = admin.firestore().collection('account_addresses').where('accountID', '==', account.id);
return query.get().then(addresses => {
var promises = [];
addresses.forEach(address=>{
promises.push(address.ref.delete());
})
return Promise.all(promises);
}).then(()=> {
// Then run the transaction to update the account_type object
return runTransaction(transaction => {
// This code may get re-run multiple times if there are conflicts.
const acc_type = account.data().type;
const accountTypeRef = admin.firestore().doc("account_types/"+acc_type);
return transaction.get(accountTypeRef).then(accTypeDoc => {
// Do some stuff and update an object called users
transaction.update(accountTypeRef, {users: users});
return;          
})
})
})
.catch(error => {
console.log("AccountType delete transaction failed. Error: "+error);
});
})

我不认为问题来自Transaction,而是来自调用delete()forEach循环。您应该使用Promise.all()来返回一个Promise,该Promise在传递给promises数组的所有Promise(由delete()返回(都已实现时实现,请参见下文。


此外,您可以执行runTransaction(transaction => {...}),但runTransactionFirestore的一种方法。你应该做admin.firestore().runTransaction(...)


因此,以下方法应该起作用:

exports.onDeleteAccount = functions.firestore
.document('accounts/{accountID}')
.onDelete((account, context) => {
// First do the cleanup and delete addresses of the account
const query = admin.firestore().collection('account_addresses').where('accountID', '==', account.id);
return query.get()
.then(addresses => {
const promises = [];
addresses.forEach(address => {
promises.push(address.ref.delete());
})
return Promise.all(promises);
}).then(() => {
// Then run the transaction to update the account_type object
return admin.firestore().runTransaction(transaction => {
// This code may get re-run multiple times if there are conflicts.
const acc_type = account.data().type;
const accountTypeRef = admin.firestore().doc("account_types/" + acc_type);
return transaction.get(accountTypeRef).then(accTypeDoc => {
// Do some stuff and update an object called users
transaction.update(accountTypeRef, { users: users }); 
})
})
})
.catch(error => {
console.log("AccountType delete transaction failed. Error: " + error);
});
})

相关内容

  • 没有找到相关文章

最新更新