Introduction
In JavaScript, Promises are used to handle asynchronous operations like API calls, timers, data loading, and file operations. Promises give you cleaner, more readable async code compared to callbacks.
Basic Promise Structure
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation completed!");
} else {
reject("Something went wrong.");
}
});
Using .then() and .catch()
You handle the result of a Promise using then() and catch():
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
Real Example – Simulated API Request
function loadData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("User data loaded.");
}, 1500);
});
}
loadData().then(msg => console.log(msg));
Promise States
- pending – still running
- fulfilled – completed successfully
- rejected – an error happened
Promise.all()
Runs multiple promises at the same time and waits for all of them.
Promise.all([
fetch("/api/user"),
fetch("/api/settings")
]).then(() => {
console.log("Everything loaded!");
});
async / await (Modern Syntax)
You will learn async/await later, but here’s a preview:
async function getData() {
const result = await loadData();
console.log(result);
}
getData();
What's Next?
Promises are the foundation of modern JavaScript. After this, you're ready to learn async/await, error handling, and how real API requests work in web apps.