Promises: then catch finally Promise.all
Create and chain Promises, handle errors in catch blocks, run cleanup in finally, and run multiple Promises in parallel with Promise.all.
What Is a Promise?
A Promise represents a value that will be available in the future. It's an object in one of three states: pending (initial), fulfilled (resolved with a value), or rejected (failed with a reason). Once settled, a Promise's state is permanent.
Creating a Promise
Create a Promise with the new Promise(executor) constructor. The executor function receives resolve and reject callbacks. Call resolve with the success value or reject with an error.
const delay = (ms) => new Promise((resolve) => {
setTimeout(resolve, ms);
});
const fetchData = (url) => new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(resolve)
.catch(reject);
});All lessons in this course
- The Event Loop: Call Stack Queue Microtasks
- Callbacks and Callback Hell
- Promises: then catch finally Promise.all
- async/await and Error Handling