A Promise is an object that represents the eventual completion or failure of an asynchronous operation.
In simple words:
A Promise tells JavaScript: I will give you teh result later.
Why Promises Were Introduced
Before Promises, JavaScript used callbacks for async tasks, which led to:
- Callback hell
- Difficult error handling
- Poor readability
Promises solve these problems by making async code:
Cleaner
More readable
Easier to manage
Promise States
A Promise can be in one of three states:
- Pending – Initial state (operation not completed yet)
- Fulfilled – Operation completed successfully
- Rejected – Operation failed
Once settled (fulfilled or rejected), the state cannot change.
Creating a Promise
Syntax
let promise = new Promise(function (resolve, reject) { // async task});- resolve() - success
- reject() - failure
Example
let promise = new Promise(function (resolve, reject) { let success = true;
if (success) { resolve("Task completed successfully"); } else { reject("Task failed"); }});Consuming a Promise (then, catch)
promise .then(function (result) { console.log(result); }) .catch(function (error) { console.log(error); });Explanation
- .then() handles success
- .catch() handles errors
Promise with Asynchronous Task
let fetchData = new Promise(function (resolve, reject) { setTimeout(() => { resolve("Data fetched"); }, 2000);});
fetchData.then(data => console.log(data));Output (after 2 second)
Data fetchedChaining Promises
Promises can be chained to perform multiple async operations sequentially.
let task = new Promise(resolve => resolve(5));
task .then(result => result * 2) .then(result => result + 10) .then(result => console.log(result));Output
20Clean
Readable
No nesting
Handling Errors in Promise Chain
new Promise((resolve, reject) => { reject("Something went wrong");}).then(result => console.log(result)).catch(error => console.log(error));Output
Something went wrongErrors automatically propagate down the chain
Promise.all()
Executes multiple promises in parallel.
Promise.all([ Promise.resolve(10), Promise.resolve(20), Promise.resolve(30)]).then(values => console.log(values));Output
[10, 20, 30]Resolves when all promises succeed
Fails if any one fails
Promise.race()
Returns the result of the first promise to settle.
Promise.race([ new Promise(resolve => setTimeout(resolve, 100, "First")), new Promise(resolve => setTimeout(resolve, 200, "Second"))]).then(result => console.log(result));Output
FirstReal-World Uses of Promises
- API calls (fetch)
- File loading
- Database queries
- Timers
- Network requests
When to Use Promises
- Multiple async operations
- Avoiding callback hell
- Better error handling
- Clean async flow
Two Minute Drill
- A Promise represents a future result
- Promise has 3 states: pending, fulfilled, rejected
- then ( ) handles success
- catch ( ) handles errors
- Promise chaining avoids nested callbacks
- Promise.all ( ) runs tasks in parallel
- Promises improve async code readability
