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?