0

I would like to add a 3-second delay between recursions in my Firebase Cloud Function. However, when I use setTimeout(), as shown in the code below, the function generates an "invalid callback" error. The delayed recursion does still work, though, but it comes with an error. And this is because I'm returning setTimeout() and not the function itself (which itself returns a promise). This function must obviously ultimately return a promise and I'm breaking the chain with setTimeout().

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

    try {
        await deleteReportDocuments(uId);
        return Promise.resolve(uId);
    } catch (error) {
        throw new functions.https.HttpsError("unknown", "Failed to delete user.", error);
    }
});

async function deleteReportDocuments(uId) {
    try {
        const db = admin.firestore();
        const snapshot = await db.collection("reports").where("author", "==", uId).limit(500).get();

        if (snapshot.size > 0) {
            const batch = db.batch();

            for (const doc of snapshot.docs) {
                batch.delete(doc.ref);
            }
            await batch.commit();
        }
        if (snapshot.size === 500) {
            return setTimeout(deleteReportDocuments(uId), 3000); // <-- delaying recursive call, generates error
        }
        return Promise.resolve();
    } catch (error) {
        throw new functions.https.HttpsError("unknown", "Failed to delete report documents.", error);
    }
}

If instead of return setTimeout(deleteReportDocuments(uId), 3000);, I simply return the function, this resolves the error and the function works perfectly but there is no delay between recursions.

if (snapshot.size === 500) {
    return deleteReportDocuments(uId);
}

Therefore, how can I properly delay the recursions in this function?

lurning too koad
  • 2,698
  • 1
  • 17
  • 47
  • 1
    Why not just write a normal iterative loop and [sleep](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) inside it? – Doug Stevenson Aug 14 '22 at 19:07
  • 3
    How is this different from the [question](https://stackoverflow.com/questions/73354410/how-to-add-a-delay-between-recursions-while-not-breaking-the-promise-chain you posted yesterday and since then deleted? If it is still the same problem, please **edit** your existing question going forward instead of reposting it - as the latter is against the rules of Stack Overflow and may get you banned. – Frank van Puffelen Aug 14 '22 at 19:26
  • @FrankvanPuffelen yesterday's question was whether or not `setTimeout` was safe to use in a cloud function. This question is how to delay recursion while not breaking the promise chain. Similar questions but very different. – lurning too koad Aug 14 '22 at 19:42

0 Answers0