Javascript promise with example

Javascript Promise are used to handle asynchronous operations. They are easy to manage when dealing with multiple asynchronous operations. In this tutorial we will see uses of javascript promise with example. So let’s get started javascript promise with example

Benefits of Promises

  • Improves Code Readability
  • Better handling of asynchronous operations
  • Better flow of control definition in asynchronous logic
  • Better Error Handling

A Promise has four states:

  • fulfilled: Action related to the promise succeeded
  • rejected: Action related to the promise failed
  • pending: Promise is still pending i.e not fulfilled or rejected yet
  • settled: Promise has fulfilled or rejected

Let see the promise syntax

var promise = new Promise(function(resolve, reject){
     //do something
});

Promise constructor takes only one argument, a callback function. Callback function takes two arguments, resolve and reject. Perform operations inside the callback function and if everything went well then call resolve. If desired operations do not go well then call reject.

Example: Promise

var promise = new Promise(function(resolve, reject) { 
  const x = "w3path"; 
  const y = "w3path"
  if(x === y) {
    resolve(); 
  } else { 
    reject(); 
  } 
})
.then(function () { 
    console.log('Success! Its working'); 
})
.catch(function () { 
    console.log('Failed! It has some error'); 
}); 

Output:

 Success! Its working 

then() is invoked when a promise is either resolved or rejected.

then() method takes two functions as parameters.

First function is executed if promise is resolved and a result is received.

Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method. We will discuss catch() method later

Syntax:

.then(function(result){
   //handle success
}, function(error){
   //handle error
})

Example: Promise Resolved

var promise = new Promise(function(resolve, reject) { 
    resolve('Success! Its working'); 
})
.then(function(successMessage) { 
   //success handler function is invoked 
    console.log(successMessage); 
}, function(errorMessage) { 
    console.log(errorMessage); 
}) 

Output:

Success! Its working

Examples: Promise Rejected

var promise = new Promise(function(resolve, reject) { 
    reject('Promise Rejected') 
})
.then(function(successMessage) { 
    console.log(successMessage); 
}, function(errorMessage) { 
   //error handler function is invoked 
    console.log(errorMessage); 
}) 

Output:

Promise Rejected

catch() is invoked when a promise is either rejected or some error has occurred in execution.

Parameters:

catch() method takes one function as parameter. Function to handle errors or promise rejections.

Syntax:

.catch(function(error){
   //handle error
})

Examples: Promise Rejected

var promise = new Promise(function(resolve, reject) { 
    reject('Promise Rejected') 
})
.then(function(successMessage) { 
    console.log(successMessage); 
}) 
.catch(function(errorMessage) { 
   //error handler function is invoked 
    console.log(errorMessage); 
}); 

Finally

Just like there’s a finally clause in a regular try {…} catch {…}, there’s finally in promises.

The call .finally(f) is similar to .then(f, f) in the sense that it always runs when the promise is settled: be it resolve or reject.

finally is a good handler for performing cleanup, e.g. stopping our loading indicators, as they are not needed any more, no matter what the outcome is.

Examples: Promise with finally

new Promise((resolve, reject) => {
  resolve('Success! Its working')
})
.then(function(){

})
.finally(function() {
  // runs when the promise is settled, doesn't matter successfully or not

})

It’s not exactly an alias of then(f,f) though. There are several important differences:

  • A finally handler has no arguments. In finally we don’t know whether the promise is successful or not. That’s all right, as our task is usually to perform “general” finalizing procedures.
  • A finally handler passes through results and errors to the next handler.
  • Last, but not least, .finally(f) is a more convenient syntax than .then(f, f): no need to duplicate the function f.

Preview

12 Comments

  1. Nida Doeberling said:

    tҺe website іѕ really good, I love your web site!

    April 13, 2020
    Reply
  2. cpa accounting said:

    Excellent write-up. I definitely love this website. Thanks!

    July 4, 2020
    Reply
  3. generic propecia said:

    Thank you for every one of your hard work on this web page. My daughter really loves making time for investigations and it’s really obvious why. Most people learn all of the lively mode you offer priceless tactics through this web site and even inspire participation from some other people on the matter so our favorite girl is now starting to learn a lot of things. Take advantage of the rest of the year. You are always doing a remarkable job. https://harrington-service.com/

    January 7, 2021
    Reply
  4. aripiprazole online said:

    I simply wanted to thank you very much once more. I do not know what I would have tried without these techniques shared by you regarding that subject matter. It was before an absolute scary scenario in my position, nevertheless taking note of this specialized tactic you solved the issue took me to weep with happiness. Now i’m thankful for your support and in addition hope that you know what a great job you are always getting into teaching people thru your web blog. More than likely you have never got to know any of us. https://abilifyaripiprazoles.com/

    January 8, 2021
    Reply
  5. generic bupron said:

    Thank you for every one of your hard work on this web page. My daughter really loves making time for investigations and it’s really obvious why. Most people learn all of the lively mode you offer priceless tactics through this web site and even inspire participation from some other people on the matter so our favorite girl is now starting to learn a lot of things. Take advantage of the rest of the year. You are always doing a remarkable job. https://bupronbupropion.com/

    January 8, 2021
    Reply
  6. risnia said:

    A lot of thanks for all your efforts on this site. Gloria loves engaging in investigation and it’s easy to understand why. Almost all know all concerning the dynamic means you give helpful items on the web blog and as well encourage contribution from others on that concern plus our daughter is actually discovering a lot. Have fun with the remaining portion of the new year. You’re the one conducting a good job. https://risniarisperidone.com/

    January 8, 2021
    Reply
  7. https://www.vfv79.com/ said:

    With low mail-open rates I wouldn’t think it was effective. Tweet seems like a cool idea.How’d you do the magic – finding twitter handle of people who comment and all that?
    Btw I learned another gem from you – you tweeted letting me know you left a response on my comment. And sort of solved my problem – I used to send individual mails to my readers letting them know I responded to their comment on my blog.
    카지노사이트

    January 12, 2021
    Reply
  8. https://txt2080.com/ said:

    Appreciate the tweet and kind words, Shiv. Hope you are having a great day!
    You’re writing a book? Awesome! I’d be thrilled if you included a paragraph to the post and linked to it in your book. (I wouldn’t mind being mentioned by name either. Haha.) Hope your readers find it useful!
    바카라사이트

    January 12, 2021
    Reply
  9. https://liveone9.com/ said:

    You’re not alone — I used to put the bare minimum into my blog comments, too. “Going through the motions” is how I used to refer to it!
    Hope this comment finds you doing well, Bramwel. Thanks again for commenting.
    모바일카지노

    January 12, 2021
    Reply
  10. https://txt2080.com/ said:

    Its always overlooked skill as most bloggers go on overdrive to link build. Of paramount importance is to understand the post before commenting as always an off topic of general comment is often taken 
    Hope you’re having a great week. Thanks again for commenting, Ahmed.
    카지노사이트

    January 13, 2021
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *