visit
Handling asynchronous operations in Javascript is a fundamental part of creating responsive and interactive web applications. Asynchronous programming allows tasks like API calls, file reading, or timers to run in the background, ensuring the application remains responsive. Enter JavaScript Promises, a powerful abstraction for managing these asynchronous operations.
A Promise in JavaScript represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A promise can be in one of three states:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation here
if (/* operation successful */) {
resolve('Success');
} else {
reject('Error');
}
});
Once a promise is created, it can be used with then()
, .catch()
, and .finally()
methods to handle the fulfilled or rejected state.
myPromise
.then((value) => {
// Handle success
console.log(value);
})
.catch((error) => {
// Handle error
console.error(error);
})
.finally(() => {
// Execute cleanup or final operations
console.log('Completed');
});
.then()
allows you to chain multiple promises, creating a sequence of asynchronous operations that execute one after the other.
fetch('//api.example.com/data')
.then(response => response.json())
.catch(error => console.error('Failed to fetch data:', error));
Error propagation in promises ensures that if an error is not caught by a .catch()
in the chain, it will bubble up to the next .catch()
.
When you need to run multiple promises in parallel and wait for all of them to complete, Promise.all()
is incredibly useful.
Promise.all([promise1, promise2, promise3])
.then((results) => {
// results is an array of each promise's result
console.log(results);
})
.catch((error) => {
// If any promise is rejected, catch the error
console.error("A promise failed to resolve", error);
});
Promise.race()
is similar to Promise.all()
, but it resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
Promise.race([promise1, promise2, promise3])
.then((value) => {
// Value of the first resolved promise
console.log(value);
})
.catch((error) => {
// Error of the first rejected promise
console.error(error);
});
Promise.allSettled([promise1, promise2, promise3])
.then((results) => {
results.forEach((result) => console.log(result.status));
});
Promise.any()
takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.
Promise.any([promise1, promise2, promise3])
.then((value) => {
console.log(value);
})
.catch((error) => {
console.error('All promises were rejected');
});
fetch('//api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
const fs = require('fs').promises;
fs.readFile('path/to/file.txt', 'utf8')
.then(data => console.log(data))
.catch(error => console.error('Read file error:', error));
async function fetchData() {
try {
const response = await fetch('//api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
async/await is syntactic sugar over promises and can be used wherever promises are used.
Also published .