Skip to content

Latest commit

 

History

History
94 lines (65 loc) · 2.22 KB

File metadata and controls

94 lines (65 loc) · 2.22 KB

Promises in JavaScript

A promises is a javascript object that allows you to make asynchronous calls.
It produces a value when async operation completes successfully or produces an error if it doesn't complete.

You can create promise using constructor:

let promise = new Promise (function(resolve, reject){

})

Executor function takes two arguements:-

  • resolve - indicate successful completion
  • reject - indicates an error

The Promise Objects and States

The Promise Object should be capable of informing consumers when execution has been started, completed in returned with an error.

  1. State
    • pending - when execution function starts
    • fulfilled - when promise resolved successfully
    • rejected - when the promise rejects
  2. result
    • undefined - initially when state value is pending
    • value - when promise is resolved
    • error - when the promise is rejected

A promise that is either resolved or rejected are settled.

Handling Promises by Consumer

Three important handler methods:

  • then()
  • catch()
  • finally()

These methods helps us create a link between executor and consumer.

The .then() Promise Handler

It is used to let consumer know outcome of promise. It accept two arguements:

  • result
  • error

E.g.

promise.then(
    (result) => {
        console.log(result);
    },
    (error) => {
        console.log(error);
    }
);

The .catch() Promise Handler

To handle error(rejections) from Promises. It's better syntax to handle error than handling it with .then()

E.g.

promise.catch(function(error){
    console.log(error);
});

The .finally() Promise Handler

The funally() handler method performs cleanups like stopping a loader, closing a live connection and so on.
Irrespective of whether promise resolve or rejects, the finally() method will run.

E.g.

promise.finally( () => {
    console.log('Promise Settled');
}).then((result) => {
    console.log({result});
});

Important point to note,

The finally() method passes through result or error to the next handler which can call a .then() or .catch() again.