0

I am using async/await on my Firebase Cloud Functions with Firestore, as they seems to be supported (maybe not officially?).

However I noticed that some of my code is not being executed before the function ends. I always see in my logs that a function finished and a couple of minutes later I see the logs from one part of my function.

I cannot share the exact code of my function but it looks like this (I redacted some parts):

exports.newMessages = functions
    .region('europe-west1')
    .firestore
    .document('/REDACTED/{id1}/REDACTED/{id2}')
    .onCreate(async (snap, context) => {

        // some code removed

        // get the a list of documents
        const someDocs = await someDocuments(context.params.id, context.params.id2);

        someDocs.forEach(async snap => {
            let uid = snap.data().uid;

            if (someCondition) {
                await quickOperation(context.params.id, context.params.id2, uid);
                await sendPushNotification(uid);
            }
        })

        await anotherOperation();
    });

The logs inside quickOperation and anotherOperation appear before the Function execution took ... log line. But the logs inside sendPushNotification appear after that log line, and about two minutes later.

The code inside sendPushNotification performs a series of reads in Firestore and then performs a push notification. This would happen even two minutes after the cloud function run.

  • Is the fact that I am using Async/Await the one to blame here?
  • Would refactoring and using TypeScript (which also supports Async/Await) help in any way?
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Miguel Beltran
  • 2,132
  • 1
  • 23
  • 36
  • 1
    This has nothing to do with Cloud Functions. You can't use async/await in a foreach callback like that. Either find a way to iterate that doesn't involve a callback, or collect the promises into an array and use Promise.all to wait for all of the work to complete. – Doug Stevenson Jul 14 '19 at 15:51
  • Thanks for the hint and the quick response! – Miguel Beltran Jul 14 '19 at 15:57
  • just to add: that was it, switching to a simple for loop over `.docs` worked. – Miguel Beltran Jul 14 '19 at 16:10

0 Answers0