Javascript - Promises in ES6

Introduction

Promise is here to solve the "Callback Hell."

Consider the following code example, where X must happen before Y and y must happen before Z:

x = getData(); 
y = getMoreData(x); 
z = getMoreData(y); 

Without promises, you could have asynchronously fetched x and then passed it as an argument to fetch y and similarly for z, using callbacks as follows:

getData(function(x){ 
    getMoreData(x, function(y){ 
        getMoreData(y, function(z){ 
            ... 
        }); 
    }); 
}); 

Promises handle asynchronous processing in a more controlled pattern.

They represent a value that can be handled in the future.

Promises provide a simpler alternative for executing, composing, and managing asynchronous operations in comparison to callback-based approaches.

ES6 promise is an object that is waiting for an asynchronous operation to complete.

When that operation completes, the promise is either fulfilled or rejected.

A promise object can be any of these three states:

  • fulfilled ? when the promise succeeds
  • rejected ? when the promise fails
  • pending ? when it's neither fulfilled or rejected

A pending promise may transition into a fulfilled or rejected state.

The promise is settled when it's either fulfilled or rejected.

A settled promise is immutable. Once a promise is settled, it cannot be resettled.

Related Topics