JavaScript Promises Cheat Sheet
1. Creating a Promise
const promise = new Promise((resolve, reject) => {
// Async operation
const success = true;
if (success) {
resolve('Operation was successful');
} else {
reject('Operation failed');
}
});
2. Using `.then()` and `.catch()`
then()
: Handles successful fulfillment of a promise.catch()
: Handles promise rejection.
const promise = new Promise((resolve, reject) => {
const success = true;
success ? resolve('Success!') : reject('Failure');
});
promise
.then(result => console.log(result)) // 'Success!'
.catch(error => console.error(error)); // 'Failure'
3. Returning a Value from `.then()`
const promise = new Promise((resolve, reject) => resolve('Step 1'));
promise
.then(result => {
console.log(result); // 'Step 1'
return 'Step 2';
})
.then(result => {
console.log(result); // 'Step 2'
});
4. Chaining `.then()`
Promises can be chained to handle multiple sequential async operations.
const promise = new Promise((resolve, reject) => resolve(1));
promise
.then(result => result * 2) // 1 * 2 = 2
.then(result => result + 3) // 2 + 3 = 5
.then(result => console.log(result)); // 5
5. `Promise.all()`
Promise.all()
is used when you need to wait for multiple promises to resolve.
const promise1 = Promise.resolve(10);
const promise2 = Promise.resolve(20);
Promise.all([promise1, promise2])
.then(results => console.log(results)); // [10, 20]
- If any promise rejects,
Promise.all()
will reject immediately.
const promise1 = Promise.resolve(10);
const promise2 = Promise.reject('Error!');
Promise.all([promise1, promise2])
.catch(error => console.error(error)); // 'Error!'
6. `Promise.race()`
Promise.race()
returns the result of the first promise that resolves or rejects.
const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'First'));
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 200, 'Second'));
Promise.race([promise1, promise2])
.then(result => console.log(result)); // 'First' (faster one)
7. `Promise.allSettled()`
Promise.allSettled()
waits for all promises to settle (either resolve or reject).
const promise1 = Promise.resolve(10);
const promise2 = Promise.reject('Error');
Promise.allSettled([promise1, promise2])
.then(results => console.log(results));
// [{ status: 'fulfilled', value: 10 }, { status: 'rejected', reason: 'Error' }]
8. `Promise.any()`
Promise.any()
returns the first resolved promise, or rejects if all promises are rejected.
const promise1 = Promise.reject('Error');
const promise2 = Promise.resolve(20);
Promise.any([promise1, promise2])
.then(result => console.log(result)); // 20
9. `async`/`await`
async
functions always return a promise.await
pauses the execution of an async function until the promise resolves.
async function fetchData() {
const result = await fetch('https://api.example.com/data');
const data = await result.json();
console.log(data);
}
fetchData();
10. Error Handling with `async/await`
Handle errors using try
/catch
with async/await
.
async function fetchData() {
try {
const result = await fetch('https://api.example.com/data');
const data = await result.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();