【发布时间】:2020-03-19 11:12:06
【问题描述】:
在 onDelete 触发器中,我正在运行一个事务来更新某个对象。我现在需要在运行该事务之前进行一些清理并删除一些其他对象。添加清理代码后,我收到关于嵌套承诺的警告,我不知道如何摆脱。这是一个sn-p:
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);
});
})
【问题讨论】:
-
你可以尝试使用
await,但我不确定它是否完全支持(我不使用firebase) -
我觉得乍一看没有问题。
-
@appleapple 我在 transaction.get 行上收到警告以避免嵌套承诺。如果我删除了清理代码(query.get() 调用),那么这个警告就会消失......
-
@shaimo 我的意思是使用
await没有问题,抱歉没有说清楚。 -
哦,等等,
runTransaction会返回 Promise 吗?
标签: javascript node.js firebase google-cloud-firestore google-cloud-functions