Introduction to Promises in JavaScript

·

4 min read

Introduction to Promises in JavaScript

Photo by Ben White on Unsplash

Dear reader, I am here with you with one of the must-know concepts in JavaScript, which helps to deal with asynchronous tasks effectively. I will promise you at the end of this short article to introduce you to its fundamentals to get familiar with all the methods. If you already have some knowledge about Promises already ex: consuming promises, and chaining promises I would say find Part 2 of the article about promises to deep dive.

Promises are a relatively new addition to JavaScript, they came in part of the ES2016 specification of ECMA Script (a.k.a JavaScript).

Promise API provides a better mechanism to handle asynchronous tasks by wrapping task and providing set of methods to handle the completion and its result. fetch API in JavaScript uses promise API and its concepts internally.

Browser support

With the nature of how web standards evolve it’s important to understand browser support before we use it in a real application. Otherwise, we end up with poor browser support for the application as a whole.

source: https://caniuse.com/?search=Promises

image.png

How the Promise APIs look like?

// PartA
  const promiseInstance = new Promise((resolve, reject) => {
    setTimeOut(() => resolve('done'), 2000);
  });
// PartB
  promiseInstance.then(
    function (response) {
      console.log(response); // prints "done"
    },
    function (err) {
      console.log(err);
    }
  );

Two common usage of Promises

Before getting into some of the real-world use cases of this API, we need to understand how promises are used broadly across the application

a. creation using Constructor

This purpose involves creating a promise object using the built-in Promise constructor which returns an instance of Promise

In the above code snippet, Part A is where are creating the Promise object with new keyword and the constructor takes a callback function and callback has been provided with two of the promise methods resolve and reject to communicate the eventual status of an async task with either success or an error.

Promise constructor comes with set of methods like .all .allSettled .race .any .resolve and reject to deal with efficiently create and manage promises.

In practice creating a promise is less common, as most of the use cases involve the second purpose which is consumption.

b. consumption using its instance

As mentioned above consumption is a very common thing and it involves dealing with promise object than the creation part.

Part B of the code snippet illustrate how to use promise object to get the final result of the async operation that can be a success or a failure to complete the task which is consumption part.

To deal with consumption promise object comes with set of instance methods, they are .then .catch and .finally

Becoming good at-promise involves the constructor methods and instance methods as outlined above. In rest of this article, we will learn the consumption with some examples

Promise states

JavaScript-Promise-1.png.png img credit

A promise instance state life cycle

As you can see in the picture, a promise instance goes through three states in its lifecycle

  1. pending which is the initial state of the instance with no result of the async task
  2. based on the outcome of the task, it’s resolved if its successful and you get a result value as returned at the end.
  3. its rejected when async task completes but ends with an unsuccessful completion, which results into an error being returned to the handler.

Let's see them in action

// creating a promise to simulate the fetch data to real api
function fetchData(){
   return new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve([{name: "Arun", email: arun@gmail.com, isAdmin: false}]);
      },2000);
   });
}
//create a new Promise instance from factory function 
const promise = fetchData();

// promise in pending state
console.log({promise});

promise.then(function(response){
 console.log(response.data); 
  // prints user object [name: "Arun", email: arun@gmail.com, isAdmin: false}]
});

// promise in fullfilled state
console.log({promise});

TL; DR;

Promises are introduced part of ES6 part of the specification and they have good support from all the browsers. The understanding promise involves two parts which are understanding creating a promise instance to handle the async task and consuming the promise to receive the eventual completion status and handle the control flow accordingly.

Summary

  • Promises are cool features to understand to be good at JavaScript part of ES6.
  • Promises can be created to wrap the async task and can be handled to write the logic which depends on async task result.
  • so I have fulfilled my promise to explain about promises in JavaScript, at the end, it resulted in success if you understood everything
  • otherwise, completed unsuccessful understanding with some doubts(error) in mind

References