- A promise is an object that links a time consuming “producing code” to a “consuming code” that needs the results when it's ready.
let promise = new Promise(function(resolve, reject) {
// Executor (the producing code)
});
- The function passed to
new Promise is called the executor.
- When the promise is created, this executor function runs automatically.
- It contains the producing code, that should eventually produce a result.
- The resulting
promise object has internal properties:
state: initially “pending”, then changes to either “fulfilled” or “rejected”,
result: an arbitrary value of your choosing, initially undefined.
- When the executor finishes the job, it should call one of the functions that it gets as arguments:
resolve(value): to indicate that the job finished successfully:
- sets
state to "fulfilled",
- sets
result to value.
reject(error): to indicate that an error occurred:
- sets
state to "rejected",
- sets
result to error.
let promise = new Promise(function(resolve, reject) {
if (true) {
setTimeout(() => resolve("done"), 1000);
} else {
setTimeout(() => reject(new Error("Error!")), 1000);
}
});
- The Promise that is either resolved or rejected is called “settled”, as opposed to a “pending” Promise.
- There can be only a single result or an error.
- All further calls of
resolve and reject are ignored:
let promise = new Promise(function(resolve, reject) {
resolve("done");
reject(new Error("…")); // ignored
setTimeout(() => resolve("…")); // ignored
});
- Also,
resolve/reject expect only one argument (or none) and will ignore additional arguments.
- The properties
state and result of the Promise object are internal.
- We can’t directly access them from our “consuming code”.
- We can use the methods
.then/.catch/.finally for that.
Consumers: then, catch, finally
then
promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
- The first argument of
.then is a function that:
- Runs when the Promise is resolved, and receives the result.
- The second argument of
.then is a function that:
- runs when the Promise is rejected, and receives the error.
let promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve("done!"), 1000);
});
promise.then(
result => console.log(result), // shows "done!" after 1 second
error => console.log(error) // doesn't run
);
- If we’re interested only in successful completions, then we can provide only one function argument to
.then.
promise.then(alert);
catch