Day047— Learn JavaScript Promises (Pt.1) with HTTP Triggers in Cloud Functions

Jacky Tsang
2 min readApr 14, 2018

--

Today I watched a Firebase tutorial from the official Firebase Youtube channel. Since I do projects alone all the time, Firebase as a serverless seems to be a good fit for helping me along the development period. I have used Firebase on Android for its real-time database for quite some time now. I think it is time for me to learn the remaining part of its kit.

A promise represents some asynchronous work that should eventually complete.

There are three states in Promise:

  1. pending
  2. fulfilled
  3. rejected

Once the promise being fulfilled or rejected, it cannot be changed again. A promise is return before the work is completed. Use .then() to do subsequent things when the promise is fulfilled, use .catch() to trap error for the rejected case. .then() method returns a Promise that is fulfilled or rejected.

Rules for terminating a Cloud Function (1:38/08:50)

  1. HTTP triggers — send a response at the end
  2. Background triggers — return a promise (next video in the series)

First, for HTTP type triggers, they’re terminated after they send a response to the client using the response object that it received. Second, for all other types of triggers, called background triggers, you need to return a Promise that’s fulfilled only after the work that was started in the function is fully complete. If there’s no work to wait on, you can just return null.

Run cloud function locally (06:22)

At 06:22, the host shows how to run cloud function locally.

First of all, check for error in code:

npm run-script lint

To convert TypeScript code to JavaScript one to a lib folder:

npm run-script build

To emulate functions on local machine:

firebase serve --only functions

The url for triggering function will appear in the terminal.

Execute below command to get the returned result:

curl url_copied_from_terminal

At 07:33, Remember to send things back to client, both success and error. Otherwise, the function will time out.

At 07:56, the code is cleaned up by chaining all promise functions together for readability.

A side note,

Choose a Database: Cloud Firestore or Realtime Database

Firebase offers two cloud-based, client-accessible database solutions that support realtime data syncing:

  • Realtime Database is Firebase’s original database. It’s an efficient, low-latency solution for mobile apps that require synced states across clients in realtime.
  • Cloud Firestore is Firebase’s new flagship database for mobile app development. It improves on the successes of the Realtime Database with a new, more intuitive data model. Cloud Firestore also features richer, faster queries and scales better than the Realtime Database.

--

--

No responses yet