Javascript – Promise Concept Explained with Code Samples

0
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

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, .NET, C/C++, mobile programming languages etc and, computing fundamentals such as application security, cloud computing, API, mobile apps, google glass, big data etc.Recently, he has been digging deep into the field of data science and machine learning.

Follow him on Twitter and Google+.
Ajitesh Kumar

Leave A Reply