Understanding Promises in JavaScript
A comprehensive guide to understanding how Promises work in JavaScript.
1. What is a Promise?
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to write asynchronous code in a more manageable way.
Promises have three states:
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully, resulting in a resolved value.
- Rejected: The operation failed, resulting in a reason for the failure.
2. Creating a Promise
You can create a Promise using the Promise
constructor, which takes a function with two parameters: resolve
and reject
.
const p = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Hello, Death Code");
resolve();
}, 2000);
});
In this example, after 2 seconds, the message "Hello, Death Code" is logged, and the Promise is resolved.
3. Handling Promises
To handle the result of a Promise, you can use the then
and catch
methods:
p.then(() => {
console.log("After Promise Resolved");
});
This code logs "After Promise Resolved" after the Promise is resolved.
4. Example with Conditional Logic
Hereβs another example that demonstrates how to handle both resolved and rejected states:
new Promise((resolve, reject) => {
// Simulating a database call
let flag = false;
if (flag) {
setTimeout(() => {
resolve();
}, 2000);
} else {
setTimeout(() => {
reject();
}, 2000);
}
}).then(() => {
console.log("Promise Resolved");
}).catch(() => {
console.log("Promise Rejected");
});
In this example, if flag
is true
, the Promise resolves; otherwise, it rejects after 2 seconds.
5. Chaining Promises
You can chain multiple then
calls to handle the resolved value:
const p2 = new Promise((resolve, reject) => {
// Simulating a database call
let flag = false;
if (flag) {
setTimeout(() => {
resolve({ name: "T-Shirt", color: "Red" });
}, 1000);
} else {
setTimeout(() => {
reject("Something went wrong");
}, 1000);
}
});
p2.then((product) => {
return product.name;
}).catch((err) => {
console.log(err);
}).then((productName) => {
console.log(productName);
});
In this example, if the Promise resolves, it returns the product name, which is then logged to the console.
6. Using Async/Await with Promises
Async/await is a syntactic sugar built on top of Promises, making asynchronous code easier to read and write:
async function handlePromise () {
try {
let data = await p2;
console.log(data);
} catch (error) {
console.log(error);
}
}
handlePromise();
In this example, the handlePromise
function uses await
to pause execution until p2
is resolved or rejected. If resolved, it logs the data; if rejected, it catches the error and logs it.
7. Conclusion
Promises are a powerful way to handle asynchronous operations in JavaScript. They provide a cleaner alternative to callbacks, allowing for better error handling and chaining of operations. By using Promises, developers can write more maintainable and readable asynchronous code.