我有一个 Firebase 函数,可以在创建新用户时发送电子邮件、更新另一个集合上的记录并在另一个 API 服务上创建帐户。整个操作运行了2分钟,但我认为还可以进一步优化。我也是异步等待的新手,所以我真的不知道如何正确使用它。
exports.onCreateUser = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => {
const updateOtherCollectionRecord = async () => {
const values...
...
return admin
.firestore()
.collection('others')
.doc('id')
.update(values);
}
const sendEmail = async () => {
const url...
...
return await axios
.post(url,data,config);
}
const createAccount = async () => {
const url...
...
return await axios
.post(url, data, config);
}
updateOtherCollectionRecord();
sendEmail();
createZendeskAccount();
})
现在,这些功能同步运行。我希望使用 Promise.all 进行重构,但不确定如何使用它。我尝试过,但它没有触发功能。
如果您的函数被声明为
async
,则在调用它们时需要使用 await
关键字。因此,您需要将云函数本身声明为 async
。
所以以下应该可以解决问题:
exports.onCreateUser = functions.firestore
.document('users/{userId}')
.onCreate(async (snap, context) => { // <=== See async here
const updateOtherCollectionRecord = async () => {
const values...
...
await admin // <=== See await here
.firestore()
.collection('others')
.doc('id')
.update(values);
}
const sendEmail = async () => {
const url...
...
await axios
.post(url,data,config);
}
const createAccount = async () => {
const url...
...
await axios
.post(url, data, config);
}
await updateOtherCollectionRecord();
await sendEmail();
await createZendeskAccount();
return null;
});
根据您在问题中的解释,没有真正需要使用
Promise.all()
:总会有三个对异步函数的调用,您可以很好地按顺序执行它们。