Will a cloud function exit early if you don't use await on a nested function?

994 views
Skip to first unread message

Steven

unread,
May 7, 2019, 10:23:07 AM5/7/19
to Firebase Google Group
Hi,

I am wondering if a cloud function will exit early if I don't use await on a nested async function that (in this case) runs a firebase transaction?

The docs say that cloud functions won't end until all promises have returned something... So in theory just calling an async function (if I understand correctly async functions are wrapped in a promise by default) will always return a promise which means, even if I don't use await, the main function should not end until the async functions that are called inside of it return something...Regardless of whether or not await was used. 

Can anyone confirm if this is correct?

I've actually tested it and it works as expected, but I am not sure if that's only because the transactions run so fast they are done before the main function terminates and if for whatever reason the transaction is running slow one day will it be cancelled before it can run due to the parent function completing. 


Hiranya Jayathilaka

unread,
May 7, 2019, 1:48:16 PM5/7/19
to fireba...@googlegroups.com
As long as you return a promise from the cloud function, it should be fine. For example:

async function someAsyncFunction(): Promise<string> {
  return "value";
}

functions.auth.user().onCreate(
  async (user, context) => {
    return someAsyncFunction(); // Returns Promise<string>; so this is ok
  });

If you want to catch errors from someAsyncFunction(), that's when you should think about return-awaiting:

functions.auth.user().onCreate(
  async (user, context) => {
    try {
      return await someAsyncFunction(); // Returns Promise<string>; await makes sure that the catch block is hit in the event of an error
    } catch (err) {
      return "error happened"; // will not reach, unless you await in the try block.
   }
  });

Hope this helps.

Thanks,
Hiranya


--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/firebase-talk/f5c4d4f5-afc3-4349-906a-6353f6cf6c9d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--

Hiranya Jayathilaka | Software Engineer | h...@google.com | 650-203-0128

Reply all
Reply to author
Forward
0 new messages