how to use promise in js , how to use promise in javascript , how to use promise js , how to use promise javascript , what is a javascript promise , promise javascript explained

What is a Javascript Promise ?

Let’s imagine you are a painter , and your fans are very crazy about your paintings who asks you day and night for upcoming paintings .

Now after seeing the crowd , you have promised your fans to get them inform about your upcoming paintings when it made available . And even if for some reason your painting could not be available your fans still get notified about it .

Now everyone becomes happy . You , because you can work without any disturbance , and your fans , because they no longer have to worry about notification of your upcoming paintings .

This is the real life analogy , and this happens in programming also . How ? Let’s see

In programming , sometimes you have to perform a task which takes some time and it’s result is needed by a lot’s of other functions . So

  • The code which is performing the time driven task is you (painter )
  • And the code which is consuming it’s result ( other functions ) are your fans .

So , Promise in javascript is a special syntax that possesses the ability to perform the time driven task and let other functions inform about the task completion , irrespective of it’s failure and success .

How Promise in Javascript works ?

Now firstly let’s see the syntax of Promise in javascript .

let greeting = new Promise(function(resolve, reject) {
  // task takes 1 second to complete and return greeting
  setTimeout(() => resolve("Hello, have a great day"), 1000);

In the above code new Promise() is the constructor for promise and the function inside it is called as “executer” . Executer accepts two parameters “resolve” and “reject” .

When task is completed successfully then with resolve it returns the result . And when task fails to complete due to some reason then it returns it’s result with reject , example is give in below code .

let greeting = new Promise(function(resolve, reject) {
  // task takes 1 second to complete and throws an error
  setTimeout(() => reject(new Error("no greetings"), 1000);

Now in promise there is a term “state” , when task is in process of completion then the state of promise is “pending” and after the completion of task state of promise changes to “fulfilled” or “rejected” according to the success or failure of task . - How to use Promise in Javascript
Javascript Promise working flow

Consumer : .then() and .catch() in Javascript Promise

Now when result of promise is avaiable to use , then the consumer function .then() and .catch() is used to recieve the result and make use of it .

.then() in Javascript Promise

First let’s see the syntax of .then()

  function(result) { /* if promise is resolve then this function will run*/ },
  function(error) { /* if promise is rejected then this function will run */ }

.then() acceptes two functions , one if for resolved promise and another one is rejected promise .

First function runs only when promise is resolved then the result is stored in the result argument of first function .

Second fucntion runs only when promise is rejected then the error is stored in the error argument of second function .

.catch() in Javascript Promise

Now if you are only interested in error of promise then can simply use .catch() to handle rejected promise .

Let’s see the syntax

greeting.catch(alert); // runs only if greeting promise is rejected 

.catch() is only used to handle the error of a promise . You can also use .then() to handle only error of a promise by passing null to the first function , like : .then(null, function(error) { // error handling code } )

.finally() in Javascript Promise

Like the try{ } and catch(){ } block javascript promise also have finally() which runs automatically in both the cases resolved and rejected of a promise .

And syntax of finally() is

   .finally(() => console.log('result recieved'))
   .then(result => console.log(result),null); // Hello , have a great day (if promise is resolved)

Now putting all the above code together we get

let greeting = new Promise(function(resolve, reject) {
  // task takes 1 second to complete and return greeting
  setTimeout(() => resolve("Hello, have a great day"), 1000);

   .finally(() => console.log('result recieved')
   .then(result => console.log(result) , 
         error => console.log(error)

// Hello , have a great day

So thats’ all about promise in javascript .

Follow me on Linkedin : Anand Raj

Join Our Telegram community of developers over here

Want to learn Firebase Chat application Development with Javascript and Jquery ? click here

Next Article : What is async await in javascript