DEV Community

Cover image for JS Promise
Vishang
Vishang

Posted on

JS Promise

A Promise is an object representing the eventual completion or failure of an async operation. Essentially, a promise is returned object to which you attach callback, instead of passing callback into a function.

A Promise is one of these states:

  • Pending: Initial(default) state, neither fulfilled nor rejected.
  • Fullfilled: Operation completed successfully
  • Rejected: Operation Failed

Pending promise can either be full-filled with a value, or rejected with a reason (error). when either of these options happens, the associated handlers queued up by a promise's then method are called.

Three main questions about the promises

    1.How to create a Promise
    2.How to change the status of a promise
    How to listen for when status of a promise changes

How to create a Promise

A Promise object is created using the new keyword and its constructor.
const promise = new Promise()

How to change the status of a promise

The Promise constructor a single callback function which takes two args. resolve callback function called when the result of the promise is resolve and reject callback function is called when the result of the promise is to rejected.

const promise = new Promise((resolve, reject)=>{
    resolve(); // When the promise is fulfilled it change the status of the promise to resolve
    reject(); // When the promise is rejected it change the status of the promise to rejected.
})
Enter fullscreen mode Exit fullscreen mode

How to listen for when status of a promise changes

We can listen to the changes to the two method available with promises.

.thenIf promise is fulfilled(resolve) the function attached to .then method is invoke
.catchIf promise is rejected(rejected) the function attached to .catch method invoke

If you log the empty promise you can see the method attached to it's prototype.

Promise console

Simple Example

Methods

Promise.all(iterable)

Returns a promise that either fulfills when all of the promises in the iterable args have fulfilled or rejects as soon as one of the promises in the iterable args rejects.

if the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in the same order as defined in the iterable.

If the returned promise rejects, it is rejected with reason from the first promise in the iterable that rejected.

Promise.race(iterable)
Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.

Promise.reject(reason)
Returns a Promise object that is rejected with the given reason.

Promise.resolve(value)
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

How promises make confusing callback code lil easier

Old ways of doing several async operation in a row will create classic callback pyramid of doom

doSomthing(function(result)){
    doSomethingElse(result, function(newResult){
        doThirdThing(newResult, function(finalResult){
            console.log(finalResult)
        }, failureCallback);
    }, failureCallback);
},failureCallback);
Enter fullscreen mode Exit fullscreen mode

With modern functions, we attach our callbacks to the returned promises instead, forming a promise chain:

doSomething()
.then(result=> doSomethingElse(result));
.then(newResult => doThirdThing(newResult));
.then(finalResult => console.log(finalResult));
.catch(failureCallback)
Enter fullscreen mode Exit fullscreen mode

Now you can compare which is easy to read and follow.

Codesandbox

Adding the codesandbox.

  1. OnClick it will call a function which is returning a promise !
    axios.get

  2. Once the promise gets resolved it will call another function ".then" which is generating an actual UI for our component.

Oldest comments (0)