Javascript – Promise Concept Explained with Code Samples

This blog represents concepts on Promise concept in Javascript with diagrams and code examples. Following is described later in the blog:

  • Promise explained with simple example
  • Promise execution timeline
  • Promise program code sample

 

Promise Explained with Simple Example
  1. Lets say, a consumer program invoked an API and asked for the output. In synchronous world, the value is returned then and there and the caller program waits for the service provider program to respond. The execution of the program halts.
  2. Welcome Promise on board! With Promise concept, the service provider program can respond with a “promise” that it would return output value or error in near future and the caller program continues with the execution.  This happens in below program as step 1, 2, 3
  3. In the meantime, the provider program executes and once the output is evaluated, the program choose to fulfill promise by invoking “resolve” or “reject”.  Once the provider program invokes the method, resolve or reject, the output is returned to called program. The caller program consumes the output. This is represented in below program with step 4 and 5.
promise_in_simple_words

promise_in_simple_words

 

Promise Execution Timeline

The diagram below represents following:

  1. The caller program invokes API and gets a Promise in return that the output will be returned in future.
  2. The caller and the provider program then continues to execute on its timeline.
  3. Once provider program evaluated the output, it invokes resolve or reject appropriately thereby returning either the value or error respectively.
Promise Execution Timeline

Promise Execution Timeline

 

Promise Program Code Sample
var p = new Promise(function (resolve, reject) {
//
// The program evaluates
//
// Invokes resolve(someObject) based on success criteria
//
// Invokes reject(error) for Error
//
});

Following diagram depicts the code sample:

Promise-code-sample

Ajitesh Kumar
Follow me

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com
Posted in Javascript, Web. Tagged with .

Leave a Reply

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