Berry Blue
Berry Blue

Reputation: 16482

How to call async functions from a Firebase Cloud Function

I'm exporting a Firebase cloud function that I can call from my iOS app.

exports.myFunction = functions.https.onCall((someData, context) => {

});

How do I call an async function?

exports.myFunction = functions.https.onCall((someData, context) => {

    return await someAsyncFunction();

});

The documentation states to return a promise but I'm not sure how to wrap an existing async function into a promise that I can return.

https://firebase.google.com/docs/functions/callable

To return data after an asynchronous operation, return a promise. The data returned by the promise is sent back to the client. For example, you could return sanitized text that the callable function wrote to the Realtime Database:

Upvotes: 5

Views: 3144

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317322

You can either make the callback function passed on onCall async so you can use await inside it:

exports.myFunction = functions.https.onCall(async (someData, context) => {
    return await someAsyncFunction();
});

Or, you can simply return the promise returned by someAsyncFunction:

exports.myFunction = functions.https.onCall((someData, context) => {
    return someAsyncFunction();
});

In either case, you are obliged to return a promise that resolves with the data to serialize and send to the client app. Both of these methods will do that.

Upvotes: 5

deepak
deepak

Reputation: 1375

Try appending async in front of function to use await.

exports.myFunction = functions.https.onCall(async(someData, context) => {

  return await someAsyncFunction();

});

Upvotes: 9

Related Questions