【问题标题】:Need help refactoring my firebase function需要帮助重构我的 firebase 功能
【发布时间】:2021-06-15 07:51:21
【问题描述】:

我有一个 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-functions


    【解决方案1】:

    如果您的函数声明为async,则在调用它们时需要使用await 关键字。因此,您需要将 Cloud Function 本身声明为 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():总是会调用三个异步函数,您可以很好地按顺序进行。

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多