JavaScript Promises: Handling Asynchronous Operations
synchronous vs asynchronous, the event loop, callbacks, Promise constructor, then, catch, finally, Promise.all, Promise.race, Promise chaining
JavaScript Promises: Handling Asynchronous Operations
JavaScript is single-threaded, meaning it can only execute one thing at a time. Yet web applications need to perform tasks that take time โ fetching data from a server, reading a file, waiting for a timer. Promises are the modern solution to handling these asynchronous operations cleanly and without deeply nested callbacks.
The Event Loop and Asynchronous JavaScript
The JavaScript event loop allows the language to perform non-blocking operations despite being single-threaded. When an async operation (like a network request) is started, it is handed to the browser's Web APIs. When complete, a callback is placed in the task queue. The event loop picks it up when the call stack is empty.
Creating a Promise
const fetchUser = new Promise((resolve, reject) => {
const success = true; // simulate a successful operation
if (success) {
resolve({ id: 1, name: 'Alice' });
} else {
reject(new Error('User not found'));
}
});
fetchUser
.then(user => console.log('Got user:', user))
.catch(err => console.error('Error:', err.message))
.finally(() => console.log('Request complete'));Promise Chaining
function getUser(id) {
return new Promise(resolve => {
setTimeout(() => resolve({ id, name: 'Alice' }), 500);
});
}
function getUserPosts(user) {
return new Promise(resolve => {
setTimeout(() => resolve([{ title: 'First Post' }]), 300);
});
}
getUser(1)
.then(user => {
console.log('User:', user.name);
return getUserPosts(user);
})
.then(posts => {
console.log('Posts:', posts);
})
.catch(err => console.error(err));Promise.all and Promise.race
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
// All must resolve โ results in order
Promise.all([promise1, promise2, promise3])
.then(values => console.log(values)); // [1, 2, 3]
// First to settle wins
Promise.race([promise1, promise2, promise3])
.then(value => console.log(value)); // 1