Promises - Basic Syntax
A promise is an object that stands in for a result which is not ready yet. A function that starts slow work, such as a network request, a file read or a timer, can return a promise at once, and the code that called it attaches callbacks that run when the work finishes.
Before promises, slow work took a callback function as an argument, and each step that depended on the one before had to be nested inside its callback. Promises let those steps be written as a flat chain instead, and they give errors one place to be handled. Many built-in APIs return promises, including fetch(), and async functions are built on them.
The three states
Section titled “The three states”A promise is always in one of three states:
- pending: the work has not finished yet.
- fulfilled: the work succeeded, and the promise holds its value.
- rejected: the work failed, and the promise holds the reason, which is usually an
Error.
A promise that is fulfilled or rejected is said to be settled. Once it has settled, its state and value do not change.
Creating a promise
Section titled “Creating a promise”The Promise constructor takes a function, called the executor, which starts the work. JavaScript runs the executor straight away and passes it two functions: resolve, to call with the value when the work succeeds, and reject, to call with the reason when it fails.
The examples on these pages simulate slow work with setTimeout, so they run anywhere. This function hands back a basket of shopping after 100 milliseconds:
const getBasket = () => new Promise((resolve) => { setTimeout(() => resolve(['bread', 'milk', 'apples']), 100); });
console.log('Asking for the basket');const promise = getBasket();console.log(promise);
promise.then((items) => { console.log(`The basket holds ${items.length} items`);});
console.log('Carrying on while we wait');This prints:
Asking for the basketPromise { <pending> }Carrying on while we waitThe basket holds 3 itemsgetBasket() returns the promise immediately, while it is still pending, so the rest of the program carries on. The callback given to then() runs later, when the timer calls resolve. Browser consoles display the pending promise differently from Node, but the order of the lines is the same.
Chaining with then()
Section titled “Chaining with then()”then() returns a new promise, which is fulfilled with whatever its callback returns. That lets each step pass its result to the next one:
const prices = { bread: 1.45, milk: 0.95, apples: 2.1 };
const lookUpPrice = (item) => new Promise((resolve) => setTimeout(resolve, 50, prices[item]));
lookUpPrice('apples') .then((price) => price * 3) .then((total) => total.toFixed(2)) .then((text) => console.log(`Three bags of apples cost £${text}`));This prints:
Three bags of apples cost £6.30setTimeout passes any arguments after the delay on to its callback, so setTimeout(resolve, 50, prices[item]) calls resolve(prices[item]) after 50 milliseconds.
Handling failure with catch()
Section titled “Handling failure with catch()”When the work fails, the executor calls reject. The chain then skips every then() callback and runs the nearest catch() callback instead:
const prices = { bread: 1.45, milk: 0.95, apples: 2.1 };
const lookUpPrice = (item) => new Promise((resolve, reject) => { setTimeout(() => { if (item in prices) { resolve(prices[item]); } else { reject(new Error(`No price for ${item}`)); } }, 50); });
lookUpPrice('cheese') .then((price) => console.log(`Cheese costs £${price}`)) .catch((error) => console.log(error.message));This prints:
No price for cheeseA catch() at the end of a chain also catches an error thrown inside any of the then() callbacks before it. Error Handling in Promises covers this in more detail, and Promises - More About shows other ways to create a promise.
Steve Griffith covers this topic in his video JavaScript ES6 Promises - Basic Syntax.