JavaScript: Promise
A Promise represents asynchronous work that is pending, fulfilled with a value, or rejected with an error.
What you will learn
- How
then,catch, andfinallyconnect - How to return a Promise from the next step
- How to handle rejected work without hiding the error
Minimal example
fetch('/api/items')
.then(response => response.json())
.then(items => showItems(items))
.catch(error => showMessage('Could not load items.'))
.finally(() => hideLoading());Each then receives the previous result. Returning a Promise waits for that asynchronous step before the next handler runs.
Common mistakes
- Always handle rejection at a suitable boundary; an unhandled rejection is hard to diagnose.
- Return the next Promise when chaining, or later handlers may run too early.
- Use
Promise.allwhen several independent operations must all finish, and decide how one failure should affect the result.