What is a Promise?
A Promise in JavaScript is used to handle asynchronous operations.
It represents a value that may be available now, later, or never.
A promise has three states:
- Pending – The operation is still running.
- Fulfilled – The operation completed successfully.
- Rejected – The operation failed.
Basic Example
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
promise
.then((message) => console.log(message))
.catch((error) => console.log(error));
Output:
Task completed
Example with setTimeout
let promise = new Promise((resolve) => {
setTimeout(() => resolve("Data loaded"), 2000);
});
console.log("Start");
promise.then((result) => console.log(result));
console.log("End");
Output:
Start
End
Data loaded
Promise Chaining
new Promise((resolve) => {
resolve("Step 1");
})
.then((msg) => {
console.log(msg);
return "Step 2";
})
.then((msg) => {
console.log(msg);
return "Step 3";
})
.then((msg) => console.log(msg));
Output:
Step 1
Step 2
Step 3
Conclusion
- Promises make asynchronous code easier to manage.
- Use
.then()
for success and.catch()
for errors. - They are often combined with Async/Await for cleaner code.
Top comments (0)