Promises

Promises

Promises - why are they so appealing?

One reason to use Promises is to run our code asynchronously, in a non-blocking manner, by making use of the browser (XHR) and APIs to retrieve data. fetch() is a good example of this.

Promises act as a placeholder for data that we expect to receive in the future. When invoked, a Promise initially and immediately returns an object that inherits properties from the Promise prototype. According to the ECMAScript spec, the Promise object contains:

  • PromiseState: Governs how the Promise will react to its .then() method. Possible values include "pending", "fulfilled", and "rejected".
  • PromiseResult: Will contain the eventual (asynchronous) return value being requested.
  • PromiseFulfillReactions: A list of functionality to execute on "fulfilled".
  • PromiseRejectReactions: A list of functionality to execute on "rejected".
  • PromiseIsHandled: For unhandled rejection tracking, this value contains a boolean indicating if the Promise has ever had a "fulfilled" or "rejected" state.

One aspect that makes Promises interesting is that they are two-pronged: after returning the Promise object previously mentioned, it then (most commonly) makes use of the browser’s XHR feature. When the browser receives a response from that request, it updates the Promise’s "state" property with "fulfilled" or "rejected", and the "result" property with the requested (recently returned) data.

Next, the code in one of the "reaction" properties, depending on the newly-updated “state” (“fulfilled” vs. “rejected"), gets added to the Job Queue (Microtask Queue)—not the Callback Queue. Once all global code has been run, and the call stack is empty, the event loop dequeues the Job Queue, which takes priority over the Callback Queue (sorry setTimeout, you’ll have to wait). Once the Promise code (from one of the “reaction” properties) is finally invoked, the returned data object from the asynchronous operation will be the input argument.

This is the deferred functionality that makes Promises so appealing because we can continue to thread through our JavaScript code, but when the Promise’s "state" is changed from "pending" and the Job Queue is ready to dequeue, the Promise will resume executing.

Photo by Andrea Piacquadio from Pexels