JavaScript Promise explained

A typical program cycle may consists of multiple operations that needs to be run in the background to achieve the ultimate objective of the program. For an example when you are trying to watch a YouTube video using your web browser, certain amount of the video file will be read and added to your browser cache and while you are playing the video, browser program will fetch the next part of the video in the back-end which allows you to watch the video uninterrupted.

Video Buffering using Promise

The processes that happened in the backed-end are call as Asynchronous operations This article is not about Asynchronous calls instead we are going to look at how to use Promises to make a call to external programs that may delay the response but we are not going to hold our program due to this delay.

A promise: is a wrapper object that can be used as a placeholder to make a call to a program that may take some time to execute such as reading from a external API, writing to disk etc. We can use this place holder to define what needs to be done once operation is completed or failed.

Below example code snipped shows a function wrapped inside a promise which can be either the fulfilled or rejected.

let sendVerificationEmail = new Promise((resolve, reject) => {

  // To simulate a web-service call we are using a timeout function in JavaScript.

  setTimeout(function(){

  // To test both resove & reject, we are checking for the odd and even number of the current second.
    let emailStatus = (new Date().getSeconds())%2 ==0;
    
    if(emailStatus=="success"){
      resolve("Please verify your email by clicking on the link");
    }else{
      reject("Unable to send the verification email");
    }

  }, 200);
});

sendVerificationEmail.then((successMessage) => {
  console.log("RESPONSE => " + successMessage);
});

Notes:

  • A promise can either be resolved or rejected. Not both.
  • There are situations you may have to connect few operations together based on the outcome. : promise chaining.
  • There are situations you may be calling multiple promises but you want to get the 1st one that was resolved. : promise raise.
  • You are calling multiples asynchronous calls and you need to make sure all the calls are either rejected or resolved. : promise all.
Cite this article as: Sam Muller, "JavaScript Promise explained," in Cyber Memos, December 16, 2019, https://cybermemos.com/developent/javascripts/javascript-promise-explained/.

One Reply to “JavaScript Promise explained”

Comments are closed.