A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.async/await is syntactic sugar on top of promises that allows writing asynchronous code in a synchronous-like manner.
🔹 Promises
- A promise can be in three states:
- Pending → initial state, neither fulfilled nor rejected
- Fulfilled → operation completed successfully
- Rejected → operation failed
Example:
const fetchData = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) resolve("Data received!");
else reject("Error occurred");
}, 1000);
});
fetchData
.then(data => console.log(data)) // "Data received!"
.catch(error => console.log(error));
.then()handles success,.catch()handles failure, and.finally()executes regardless.
🔹 Async/Await
asyncfunction always returns a promise.awaitpauses execution until the promise resolves or rejects.
Example:
function getData() {
return new Promise((resolve) => {
setTimeout(() => resolve("Hello World"), 1000);
});
}
async function fetchData() {
try {
const result = await getData();
console.log(result); // "Hello World"
} catch (error) {
console.log(error);
}
}
fetchData();
- Makes asynchronous code look linear and easier to read.
- Still uses Promises under the hood.
✅ Key Points
- Promises help avoid callback hell.
async/awaitis cleaner for sequential asynchronous operations.- Use
Promise.all()to run multiple promises in parallel.