需要帮助重构我的 firebase 函数

问题描述 投票:0回答:1

我有一个 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 进行重构,但不确定如何使用它。我尝试过,但它没有触发功能。

javascript node.js firebase google-cloud-platform google-cloud-functions
1个回答
0
投票

如果您的函数被声明为

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()
:总会有三个对异步函数的调用,您可以很好地按顺序执行它们。

© www.soinside.com 2019 - 2024. All rights reserved.