Promises

Contact Us or call 1-877-932-8228
Promises

Promises

We use promises in JavaScript for asynchonous processes: a promise represents a proxy - a stand-in - for a value not known at the time, but that is expected in the future. Promises have the following syntax:

new Promise(function(resolve, reject) {
	// body of function
});

The function supplied to the Promise is the executor, a function that will be passed to other functions via the resolve and reject arguments. The resolve and reject functions are bound to the promise; calling them fulfills (the resolve function) or rejects (the reject function) the promise. The executor function initiates some asynchronous process - once that completes, the function calls either the resolve or reject function to resolve the promise's final value, or rejects it if there is an error.

A Promise always exists in one of these states:

  • Pending: the initial state (not fulfilled nor rejected).
  • Fulfilled: the operation completed successfully.
  • Rejected: the operation failed.

A pending promise can become fulfilled with a value or rejected with a reason (an error). When either of these occurs, the handlers associated by the promise's then method are called.

At its simplest, we might use a promise for a case like the following:

var prom = new Promise(function(resolve, reject) {
	// perform some asynchronous task...
	if(/* successful */) {
		resolve('success');
	} else {
		reject('failure');
	}
});
	prom.then(function() {
	/* handle result */
}).catch(function() {
	/* error */
})

The following tables list Promise properties and methods:

Promise Properties
Property Description
Promise.length Length property whose value is 1 (number of constructor arguments)
Promise.prototype The prototype for the Promise constructor.
Promise Methods
Method Description
Promise.all(iterable) Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected.
Promise.race(iterable) Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
Promise.reject(reason) Returns a Promise object that is rejected with the given reason.
Promise.resolve(value) Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), then the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Let's look at how we can use promises to work with the XMLHttpRequest object:

Code Sample:

XHR/Demos/promise.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Promise</title>
<script type="text/javascript">
	function get(url) {
		return new Promise(function(resolve, reject) {
			var req = new XMLHttpRequest();
			req.open('GET', url);
			req.onload = function() {
				if (req.status == 200) {
					resolve(req.response);
				} else {
					reject(Error(req.statusText));
				}
			};
			req.onerror = function() {
				reject(Error("Network Error"));
			};
			req.send();
		});
	}

	get('/promise').then(function(response) {
		var msgDiv = document.getElementById("msg");
		msgDiv.innerHTML = response;
	}).catch(function(error) {
		var msgDiv = document.getElementById("msg");
		msgDiv.innerHTML = error;
	});
</script>

</head>
<body>

<div id="msg"></div>
</body>
</html>

Code Explanation

Our function get instantiates and returns a new Promise, invoking resolve or reject based on the status returned by the XMLHttpRequest() for the url parameter passed to get. We call get('/promise').then to handle the response - in our case, writing either (success or failure) to the same div, but we could have, of course, processed these different cases in different manners.

Next