Promise, async/await

Imagine you are a popular book writer, and you are planning to release a new book on a certain day. Readers who have an interest in this book are adding this book to their wishlist and are notified when published or even if the release day got postponed too. On the release day, everyone gets notified and can buy the book making all parties happy. This is a real-life analogy that happens in programming.

  1. A "producing code" is something that takes time and accomplishes something. Here it's a book writer.

  2. A "consuming code" is someone who consumes the "producing code" once it's ready. In this case, it's a "reader".

  3. The linkage between the "producing code" and the "consuming code" can be called a promise as it assures getting the results from the "producing code" to the "consuming code".

The analogy that we made is also true for the JavaScript promise object. The constructor syntax for the promise object is:

let promise = new Promise(function(resolve, reject) {
  // executor (the producing code, "writer")
});

Here, a function is passed to new Promise also known as the executor, and runs automatically upon creation. It contains the producing code that gives the result. resolve and rejects are the arguments provided by the JavaScript itself and are called one of these upon results.

  • resolve(value): a callback function that returns value upon result

  • reject(error): a callback function that returns error upon error, it returns an error object

The internal properties of promise object returned by the new Promise constructor are as follows:

  • state - initially pending, then changes to either fulfill upon resolve or rejected when reject is called

  • result - initially undefined, then changes to value upon resolve or error when reject is called

Promise with resolve and reject callbacks

Example of a promise.

Here, the promiseOne is an example of a "fulfilled promise" as it successfully resolves the values, whereas the promiseTwo is a "rejected promise" as it gets rejected. A promise that is either rejected or resolved is called a settled promise, as opposed to an initially pending promise. Consuming function from the promise can be registered using the .then and .catch methods. We can also add .finally method for performing cleanup or finalizing after previous methods have been completed.

Last updated

Was this helpful?