JavaScript Promises
Learn how to work with Promises to handle asynchronous operations in JavaScript.
Introduction to Promises
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
What is a Promise?
A Promise represents the future result of an asynchronous operation. It can be:
- Pending – Not yet complete
- Fulfilled – Completed successfully
- Rejected – Failed
Creating a Promise:
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed!");
} else {
reject("Something went wrong");
}
});
Using .then() and .catch()
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Done"));
async & await
async functions automatically return a Promise. Use await inside them to pause until a Promise resolves.
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function start() {
console.log("Waiting...");
await wait(2000);
console.log("Done waiting!");
}
start();
🔗 Using with fetch()
async function getUser() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
let data = await response.json();
console.log(data);
} catch (err) {
console.error("Error:", err);
}
}
getUser();
Practice Task
Create a function that simulates a loading process using a Promise and logs the result with async/await.
function loadData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Data loaded successfully!");
}, 1500);
});
}
async function showData() {
let result = await loadData();
console.log(result);
}
showData();