Promises In JavaScript Explained

  • Shiv
  • Shiv
  • Updated date Sep 13, 2020

Introduction

 
Promises are a really interesting feature in Jquery used to manage asynchronous events. They always allow for clear callback logic. Here, we are going to see what are promises, how to define the concept, how to use it, and how to execute a promise in an asynchronous way.
 

Basic Idea

 
Promises in Javascript are like making a promise in real life. If a bike mechanic gives a promise to service your bike by end of the day, either by end of the day he finishes his promise by servicing your bike or he fails. In Javascript, promises are similar.
 
By learning the basic idea of promise, you can easily manage asynchronous concepts in Javascript.
 

What are Promises?

  • A promise is an object that represents the return value or throws an exception that the function may eventually provide.
  • A promise is a native class of javascript
  • The promise is one of the easiest ways to achieve the asynchronous process in Javascript.
  • By using the promise in Javascript, we can make the callbacks operation easier.
  • The Promise object has three types: Pending, Resolve, and Reject.
  • When promises execute, first it will be in a pending state, similarly, it will be either resolved or rejected.
  • The pending state is the usual state of a promise before it succeeds or fails.
  • The resolve state is when the promise has completed successfully
  • The reject state is when the promise has failed.
Define a Promise 
  1. let promiseBikeService = new Promise(function(resolve, reject){  
  2.   
  3. });  
The keyword "new Promise" acts as a callback function. The callback function takes two arguments, one is "resolve" and another is "reject".
 
How to Use the Promise 
  1. let promiseBikeService = new Promise(function(resolve, reject){  
  2.    //Servicing the bike  
  3.    let doService = true;  
  4.   
  5.    if(doService){  
  6.      resolve('serviced');  
  7.    }  
  8.    else {  
  9.      reject('not serviced');  
  10.    }  
  11. });  
 How to execute a Promise
  1. promiseBikeService.then(function(fromResolve){  
  2.   console.log('The bike is' + fromResolve);  
  3. }).catch(function(fromReject){  
  4.   console.log('The bike is' + fromReject);  
  5. });  
The keyword "then" function will be triggered when the deffered is resolved.
 
The keyword "catch" function will be triggered when the deffered is rejected.
 

Summary

 
This is the basic idea of javascript promise. We have learned what is a promise, how to define a promise, and how to execute a promise. Please add your valuable comments. 
 
<Always be coding>