- ES6 provides Promise object to support deferred and asynchronous execution of JavaScript.
- The Promise object helps in resolving Blocking nature of JavaScript.
- In this demo, “We will learn to use promise object in a JavaScript code”.
- The following code contains a method squarePositiveNumber() takes a number as input and returns a promise object.The Promise object checks the input number, if the input number is negative it rejects through an error.If the input number is positive it calculates the square and resolve the promise with the computed value.Once the Promise object is resolved and rejected we can find the result using then() method.
<!DOCTYPE html> <html> <head> <script src="http://static.jsbin.com/js/vendor/traceur.js"></script> <meta charset="utf-8"> <title>Traceur ES6 Promise Object</title> </head> <body> <script> var squareOfPositiveNumber = function(number) { var myPromise = new Promise(function(resolve, reject) { if (number > 0) { resolve(number * number); } else { reject(new Error("Error:It is not a positive number.")); } }); return myPromise; }; var squarePromise1 = squareOfPositiveNumber(5); squarePromise1.then(function(result) { console.log(result); }); var squarePromise2 = squareOfPositiveNumber(-4); squarePromise2.then(null, function(error) { console.log(error.toString()); }); </script> </body> </html>
- The output of the previous code can be found in following JSBIN link.