Promises are a JavaScript feature that provides a more structured and readable way to work with asynchronous code. They represent the eventual completion or failure of an asynchronous operation, allowing you to handle the result or error in a more organized and manageable manner.
then
method, allowing you to sequence asynchronous operations in a readable manner.catch
method, making it easier to manage and propagate errors in asynchronous code.Avoiding Callback Hell (Callback Pyramids):
// Without Promises
asyncOperation1((result1) => {
asyncOperation2(result1, (result2) => {
asyncOperation3(result2, (result3) => {
// ...
});
});
});
// With Promises
asyncOperation1()
.then((result1) => asyncOperation2(result1))
.then((result2) => asyncOperation3(result2))
.then((result3) => {
// ...
});
Sequential Execution of Asynchronous Code:
// Without Promises
asyncOperation1((result1) => {
asyncOperation2(result1, (result2) => {
asyncOperation3(result2, (result3) => {
// ...
});
});
});
// With Promises
asyncOperation1()
.then((result1) => asyncOperation2(result1))
.then((result2) => asyncOperation3(result2))
.then((result3) => {
// ...
});
Error Handling:
catch
block to handle errors for a sequence of asynchronous operations.
asyncOperation1()
.then((result1) => asyncOperation2(result1))
.then((result2) => asyncOperation3(result2))
.catch((error) => {
console.error('An error occurred:', error);
});
Promise.all for Parallel Execution:
Promise.all
method, allowing parallel execution of multiple asynchronous operations and waiting for all of them to complete.
const promise1 = asyncOperation1();
const promise2 = asyncOperation2();
Promise.all([promise1, promise2])
.then((results) => {
const result1 = results[0];
const result2 = results[1];
// ...
})
.catch((error) => {
console.error('An error occurred:', error);
});
In summary, promises provide a cleaner and more organized way to work with asynchronous code, making it easier to read, write, and maintain. They address common challenges associated with callback-based code and promote better error handling and sequential execution of asynchronous operations.
Creating a Promise:
Promise
constructor takes a function with two parameters: resolve
and reject
.
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation goes here
// If successful, call resolve with the result
// If there's an error, call reject with the error
});
Resolving a Promise:
resolve
function when the asynchronous operation is successful.
const successfulPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Operation succeeded!');
}, 1000);
});
Rejecting a Promise:
reject
function when there's an error during the asynchronous operation.
const failedPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject('Operation failed!');
}, 1000);
});