Simple Promise In JavaScript

What is a Promise?

The Promise object represents the eventual completion (or failure) of an operation and its resulting value. It is used very frequently with asynchronous operations in JavaScript. In layman's terms, it provides an acknowledgment to the operation performed. If the action is a success (or pass), then it will resolve the promise else it will reject the promise.

Syntax 
  1. new Promise( function(resolve, reject) { ... } )   
Promise constructor takes a function as an argument which, in-turn, takes 2 arguments - resolve and reject. The function calls immediately the resolve or the reject handler once the action performed by the promise comes to a conclusion, i.e., a success or failure.

The handlers are called using the following syntax.
  1. Promise.then(function(){...for resolve...}).catch(function(){...for reject...})  
Example
  1. let promiseToCode = new Promise(function(resolve, reject) {  
  2.     //logic to be used in the promise  
  3.     //based on the output or result the resolve/reject will get called  
  4.     var doICode = true;  
  5.     if (doICode) {  
  6.         resolve("coding");  
  7.     } else {  
  8.         reject("sleeping");  
  9.     }  
  10. })  
  11. promiseToCode.then(function(fromResolve) {  
  12.     console.log("I am " + fromResolve);  
  13. }).catch(function(fromReject) {  
  14.     console.log("I am " + fromReject)  
  15. })  
Explanation

This is a very simple promise. In this promise, based on the condition of the promise, it will log the message.

If the "doICode" variable in the promise is made true, then it will print "I am coding", else it will print "I am sleeping".
Please feel free to give your feedback.
Ebook Download
View all
Learn
View all