lurning too koad
lurning too koad

Reputation: 2964

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

Can a cloud function safely execute async work after it has returned its promise? Consider the following pattern:

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);
    }
}

Should this pattern be avoided in Cloud Functions? My concern is that the instance that was initialized to execute this call could be deallocated before the tasks have a chance to finish since the function that initialized the instance returned a promise almost immediately after being called. Or will the server keep this instance alive to let the async work finish even though the main function has already terminated?

Upvotes: 1

Views: 649

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

What you are illustrating will reliably fail to work for the reason you stated. The final returned promise must resolve only after all other promises have resolved, otherwise the work might not complete. Cloud Functions doesn't do "background work" after the returned promise resolves. If you need to do continue some work without causing the function to fully terminate, you will need to pass that off to some other compute service (which you will likely also have to pay for).

Upvotes: 2

Related Questions