Sync, Async and Promises

It's important to manage the lifecycle of a function to ensure that it resolves properly. By terminating functions correctly you can avoid excessive charges from functions that run for too long or loop infinitely. Also, you can make sure that the Cloud Functions instance running your function does not shut down before your function successfully reaches its terminating condition or state.

Use these recommended approaches to manage the lifecycle of your functions:

  • Resolve functions that perform asynchronous processing by returning a JavaScript promise.
  • Terminate HTTP functions with res.redirect(), res.send(), or res.end().
  • Terminate a synchronous function with a return; statement.

Simplify asynchronous code with JavaScript promises

Promises are a modern alternative to callbacks for asynchronous code. A Promise represents an operation and the future value it may return. It also lets you propagate errors similar to try/catch in synchronous code. You can read about Promises in the Firebase SDK on the Firebase Blog, and Promises in general on MDN.

How promises work with Cloud Functions

When you return a JavaScript Promise to a Cloud Function, that function keeps running until the promise is resolved or rejected. To indicate that a function has completed its work successfully, the promise should be resolved. To indicate an error, the Promise should be rejected. This means you only need to handle errors that you want to.

The following code takes a Firebase Realtime Database ref and sets its value to "world!". By returning the result of set, your function is guaranteed to keep running until the asynchronous work of writing the string to the database is fully completed:

// Always change the value of "/hello" to "world!"
exports.hello = functions.database.ref('/hello').onWrite(event => {
  // set() returns a Promise. We keep the function alive by returning it.
  return'world!').then(() => {
    console.log('Write succeeded!');

Send feedback about...

Need help? Visit our support page.