⚡
Promises and Asynchronous Programming
Intermediate
110 XP
45 min
Lesson Content
Promises and Asynchronous Programming
Promises represent the eventual completion (or failure) of an asynchronous operation. They're essential for handling async code in JavaScript.
What is a Promise?
A Promise is an object that represents a value that may not be available yet. It has three states:
- Pending - Initial state, not fulfilled or rejected
- Fulfilled - Operation completed successfully
- Rejected - Operation failed
Creating Promises
const myPromise = new Promise((resolve, reject) => {
// Async operation
setTimeout(() => {
const success = true;
if (success) {
resolve('Operation successful!');
} else {
reject('Operation failed!');
}
}, 1000);
});Using Promises
myPromise
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.log('Error:', error);
})
.finally(() => {
console.log('Done!');
});Promise Methods
- Promise.all() - Wait for all promises to resolve
- Promise.race() - Returns first promise to resolve/reject
- Promise.allSettled() - Wait for all promises to settle
- Promise.resolve() - Creates resolved promise
- Promise.reject() - Creates rejected promise
Chaining Promises
fetch('/api/data')
.then(response => response.json())
.then(data => processData(data))
.then(result => displayResult(result))
.catch(error => handleError(error));Example Code
Create and use promises for asynchronous operations
// Create a promise that simulates fetching data
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: 'John', age: 30 };
resolve(data);
}, 1000);
});
}
// Use the promise
fetchData()
.then((data) => {
console.log('Data received:', data);
return data.name;
})
.then((name) => {
console.log('Name:', name);
})
.catch((error) => {
console.log('Error:', error);
})
.finally(() => {
console.log('Fetch completed');
});
// Promise.all example
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve) => {
setTimeout(() => resolve('foo'), 100);
});
Promise.all([promise1, promise2, promise3])
.then((values) => {
console.log('All resolved:', values);
});Expected Output:
Data received: {id:1,name:John,age:30}
Name: John
Fetch completed
All resolved: [3,42,foo]Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code