ECMAScript 2015 Promise
ECMAScript 2015 Promise
Promise Overview
Promises are an alternative to callbacks for delivering the results of an asynchronous computation. They require more effort from implementors of asynchronous functions, but provide several benefits for users of those functions.
The following function returns a result asynchronously, via a Promise:
function asyncFunc() {
return new Promise(
function (resolve, reject) {
···
resolve(result);
···
reject(error);
});
}
You call asyncFunc() as follows:
asyncFunc()
.then(result => { ··· })
.catch(error => { ··· });
States:
A Promise is always in one of three mutually exclusive states:
1. Before the result is ready, the Promise is `pending`. 2. If a result is available, the Promise is `fulfilled`. 3. A Promise is settled exactly once and then remains `unchanged`.
Reacting to state changes:
Promise reactions are callbacks that you register with the Promise method
then()
, to be notified of a fulfillment or a rejection.A
thenable
is an object that has a Promise-style then() method. Whenever the API is only interested in being notified of settlements, it only demands thenables (e.g. the values returned from then() and catch(); or the values handed to Promise.all() and Promise.race()).
Changing states: There are two operations for changing the state of a Promise. After you have invoked either one of them once, further invocations have no effect.
Rejecting a Promise means that the Promise becomes rejected.
Resolving a Promise has different effects, depending on what value you are resolving with:
1. Resolving with a normal (non-thenable) value fulfills the Promise. 2. Resolving a Promise P with a thenable T means that P can’t be resolved anymore and will now follow T’s state, including its fulfillment or rejection value. The appropriate P reactions will get called once T settles (or are called immediately if T is already settled).
Three ways of understanding Promises
Conceptually: calling a Promise-based function is blocking
A Promise is a container for an asynchronously delivered value
A Promise is an event emitter
Example promisifying XMLHttpRequest
The following is a Promise-based function that performs an HTTP GET via the event-based XMLHttpRequest API:
function httpGet(url) {
return new Promise(
function (resolve, reject) {
const request = new XMLHttpRequest();
request.onload = function () {
if (this.status === 200) {
// Success
resolve(this.response);
} else {
// Something went wrong (404 etc.)
reject(new Error(this.statusText));
}
};
request.onerror = function () {
reject(new Error(
'XMLHttpRequest Error: '+this.statusText));
};
request.open('GET', url);
request.send();
});
}
This is how you use httpGet():
httpGet('http://example.com/file.txt')
.then(
function (value) {
console.log('Contents: ' + value);
},
function (reason) {
console.error('Something went wrong', reason);
});