云函数在返回承诺后能否安全地执行异步工作?

Can a cloud function safely execute async work after it has returned its promise?

云函数在返回承诺后能否安全地执行异步工作?考虑以下模式:

exports.deleteUser = functions.auth.user().onDelete(async (user) => {
    const uid = user.uid;

    asyncTask1(uid);
    asyncTask2(uid); // don't wait for the last task to finish
    asyncTask3(uid); // just attempt them all and handle
    asyncTask4(uid); // the failures individually later
    return Promise.resolve(uid);
});

async function asyncTask1(uid) {
    try {
        await someAsyncWork();
        return Promise.resolve(true);
    } catch (error) {
        throw new functions.https.HttpsError("unknown", "Task 1 failed.", error);
    }
}

是否应在 Cloud Functions 中避免这种模式?我担心的是,初始化为执行此调用的实例可能会在任务有机会完成之前被释放,因为初始化实例的函数在被调用后几乎立即返回了一个承诺。或者即使主函数已经终止,服务器是否会让这个实例保持活动状态以让异步工作完成?

你所说明的内容肯定会因为你所说的原因而无法工作。最终返回的 promise 必须在所有其他 promise 都解决后才解决,否则工作可能无法完成。在返回的 promise 解决后,Cloud Functions 不做“后台工作”。如果您需要在不导致函数完全终止的情况下继续进行某些工作,则需要将其传递给其他一些计算服务(您可能还需要为此付费)。