JavaScript Promises

Promises are used to handle asynchronous requests in JavaScript.

var promise = new Promise(function(resolve, reject){
     //code
});

promise.then(function (result){
        //handle success
    }, function (error){
         //handle error
    }).catch(function () { 
         //Catch Error
	}); 
  • Promise Constructor takes Callback Function as argument
  • Callback Function takes resolve and reject arguments. If everything went well then call resolve, else call reject.
  • Promise.then() function takes success callback and failure callback arguments. If the promise was fullfilled, the success callback will be fired with the actual data passed to resolve(). If promise was rejected, the failure callback will be called. Whatever we passed to reject() will be passed as an argument to this callback
  • catch() function used to handle promise rejection.
  • Promise have one of the below states
    • Pending (Initial State, neither fulfilled nor rejected)
    • Fulfilled (Operation successfully completed)
    • Rejected (Operation Failed)
  • We can call .then on a Promise as many times as we want.

Example 1

<!DOCTYPE html>
<html>
<head>
<script> 
var promise = new Promise(function(resolve, reject) { 
const fee = 350; 
const discountFee = 550
if(discountFee < fee) { 
	resolve(); 
} else { 
	reject(); 
} 
}); 
promise.then(function () { 
		console.log('Success, You got Discount'); 
	},(error) => {
  console.log('Promise rejected.');
  console.log(error.message);
} ).catch(function () { 
		console.log('Some Error'); 
	}); 

 </script>
</head>
<body>
</body>
</html>

Example 2: Consuming a Web Service

Here XMLHttpRequest object is used to request data from a web server.

<!DOCTYPE html>
<html>
<head>
<script>
const promise = new Promise((resolve, reject) => {
  const request = new XMLHttpRequest();
  request.open('GET', 'https://www.xyz.com/courses.json');  
  request.onload = () => {
    if (request.status === 200) {
      resolve(request.response); // Got the Data. Resolve the Promise.
    } else {
      reject(Error(request.statusText)); // Status is not 200 OK, so Reject
    }
  };
  request.onerror = () => {
    reject(Error('Error fetching data.')); // Error occurred, reject the  Promise
  };
  request.send(); // send the request
});
console.log('Asynchronous request ...');

promise.then((data) => {
  console.log('Got the data! Promise fulfilled.');
  document.body.textContent = JSON.stringify(data,null,"    ");
}, (error) => {
  console.log('Promise rejected.');
  console.log(error.message);
}).catch((error) => {
  console.log('Error occurred!', error);
});
 </script>
</head>
<body>
</body>
</html>

References

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Learn more about JavaScript Important Features in our upcoming JavaScript Blog Articles.

Happy Learning!