JavaScript Promises Cheatsheet
Learn how to handle asynchronous operations in JavaScript with easy-to-understand examples. Perfect for beginners and intermediate developers looking to master Promises and async/await.
What are Promises?
Basic Promise Explanation
A Promise is like a delivery receipt - it's a guarantee that you'll get something back later. It can either succeed (resolve) or fail (reject).
// Creating a simple promise
const promise = new Promise((resolve, reject) => {
// Imagine this is checking if your order is ready
const orderIsReady = true;
if (orderIsReady) {
resolve("🎉 Here's your order!");
} else {
reject("😢 Sorry, we're out of stock");
}
});
Real-World Example
Just like waiting for a pizza delivery, Promises help you handle tasks that take time, like fetching data from a server.
// Fetching user data from a server
fetch('https://api.example.com/user')
.then(response => response.json())
.then(user => console.log('Got user:', user))
.catch(error => console.log('Oops:', error));
Working with Promises
Then & Catch
Think of .then() as 'what to do next' and .catch() as 'what to do if something goes wrong'
getUserData()
.then(user => {
console.log('Got the user!');
return user.posts; // Get user's posts next
})
.then(posts => {
console.log('Got the posts!');
})
.catch(error => {
console.log('Something went wrong:', error);
});
Making Things Wait
Need to pause for a bit? Create a delay function with Promises. Useful for animations or rate limiting.
// Create a pause function
const wait = (seconds) => {
return new Promise(resolve => {
setTimeout(resolve, seconds * 1000);
});
}
// Use it in your code
async function example() {
console.log('Starting...');
await wait(2); // Pause for 2 seconds
console.log('2 seconds later!');
}
Modern Promise Usage (Async/Await)
Making Code Easier to Read
async/await makes Promise code look more like regular step-by-step code. It's like writing a recipe - do this, then do that.
// Instead of lots of .then()
async function getUser() {
try {
const response = await fetch('/api/user');
const user = await response.json();
console.log('User:', user);
} catch (error) {
console.log('Oops:', error);
}
}
Doing Things at the Same Time
Need to do multiple things at once? Promise.all lets you run tasks in parallel, like cooking multiple dishes simultaneously.
async function getEverything() {
try {
// Start all requests at once
const [users, posts, comments] = await Promise.all([
getUsers(),
getPosts(),
getComments()
]);
console.log('Got everything!');
} catch (error) {
console.log('One of them failed:', error);
}
}
Common Patterns & Tips
Loading States
Keep track of loading states to show users something is happening, like a loading spinner.
async function loadData() {
const [isLoading, setIsLoading] = useState(false);
try {
setIsLoading(true); // Start loading
const data = await fetchData();
console.log('Done!', data);
} catch (error) {
console.log('Error:', error);
} finally {
setIsLoading(false); // Stop loading
}
}
Handling Timeouts
Don't wait forever! Add timeouts to your Promises to handle slow responses.
// Create a timeout wrapper
function withTimeout(promise, seconds) {
const timeout = new Promise((_, reject) => {
setTimeout(() => reject('Timeout!'), seconds * 1000);
});
return Promise.race([promise, timeout]);
}
// Use it
try {
const result = await withTimeout(fetch('/api/data'), 5);
console.log('Got data before timeout!');
} catch (error) {
console.log('Too slow or error:', error);
}