首页 > 解决方案 > 具有多个触发器的云函数 - 计划和 onCall

问题描述

我有一个云功能,每当用户在网络应用程序上执行一组操作并且每天在指定时间执行一组操作时,我都想运行它。为了不重复代码和未来的功能/错误修复,我想从一个函数/文件中运行两者。

对此流程的任何建议/参考将不胜感激!

标签: firebasegoogle-cloud-functions

解决方案


您可以在一个函数中编写业务逻辑,从两个云函数调用该函数。大致如下,具有异步业务逻辑和使用async/await

exports.myFunctionCalledFromTheApp = functions.https.onCall(async (data, context) => {
    try {
        const result = await asyncBusinessLogic();
        return { result: result }
    } catch (error) {
        // ...
    }
});

exports.myFunctionCalledByScheduler = functions.pubsub.schedule('every 24 hours').onRun(async (context) => {
    try {
        await asyncBusinessLogic();
        return null;
    } catch (error) {
        // ...
        return null;
    }
});


async function asyncBusinessLogic() {
    
    const result = await anAsynchronousJob();
    return result;
    
}

推荐阅读