OVERVIEW
Promises are a way of handling asynchronous events in javascript. Prior to promises, the only true asynchronous feature was in XMLHttpRequest where ajax calls were made.
A Promise is an object whose constructor takes in an anonymous function. The anonymous function has two arguments – resolve and reject. When the code within the anonymous functions finishes, it can either call resolve or reject . Resolve means it was successful and Reject means that some problem or error occurred.
The constructor defines the actual processing code and the calls to resolve and reject. The handling of the resolve and reject callback functions are done using the then and catch method of the Promise object. The then method will be called if resolve was executed. The catch method will be called if reject was executed.
The sample source is given below:
<html>
<head>
<title>Javascript Promises</title>
<script>
function doIt() {
var promise = new Promise(function(resolve, reject) {
var x = Math.floor(Math.random()*10);
if (x % 2 == 0)
resolve(x);
else
reject(x);
});
promise.then(function(x) {
alert(x + " was even");
}).catch(function(x) {
alert( x + " was not even");
});
}
</script>
</head>
<body>
<button type=button onclick="doIt(); return false;">Click Me</button>
</body>
</html>
Depending on whether the random number is even or odd, the relevant alert will show.
Leave a Reply