Promises confused me for a long time.
I kept reading definitions like "a promise is an object that represents
the eventual completion or failure of an async operation" and I just
stared at the screen.
So let me explain it the way I wish someone explained it to me.
What is a Promise in simple words
Think about ordering food at a restaurant.
You order, the waiter says okay and walks away. You don't sit there
frozen waiting. You talk to your friends, drink water, do other things.
When the food is ready the waiter comes back either with your food
or says sorry we ran out of that.
That is a Promise. You asked for something. It is being worked on.
Either it succeeds or it fails. Meanwhile everything else keeps going.
How it looks in code
const myPromise = new Promise(function(resolve, reject) {
let success = true;
if (success) {
resolve("it worked");
} else {
reject("something went wrong");
}
});
resolve means it went well.
reject means something failed.
How to use the result
myPromise
.then(function(result) {
console.log(result); // "it worked"
})
.catch(function(error) {
console.log(error); // "something went wrong"
});
.then runs when the promise resolves.
.catch runs when the promise rejects.
Simple as that.
A real example — fetching data
This is where you will actually use promises every day.
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data.name);
})
.catch(function(error) {
console.log("error happened:", error);
});
fetch returns a Promise. When the data comes back .then runs.
If something fails .catch handles it.
You will write this pattern a lot.
Three states of a Promise
A Promise is always in one of these three states:
Pending — still waiting, not done yet
Fulfilled — it worked, resolve was called
Rejected — it failed, reject was called
Once a Promise is fulfilled or rejected it does not change.
It stays that way.
async and await — cleaner way to write the same thing
Instead of chaining .then and .catch you can use async await.
It is the same thing just easier to read.
async function getUser() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const data = await response.json();
console.log(data.name);
} catch (error) {
console.log("something went wrong:", error);
}
}
getUser();
await tells JavaScript to wait for the Promise to finish before
moving to the next line. But only inside an async function.
try catch is the async await version of .then and .catch.
Both do the exact same thing. Most people prefer async await because
it reads like normal code.
Promise.all — when you need multiple things at once
Sometimes you need to fetch two or three things at the same time
and wait for all of them to finish.
const promise1 = fetch("https://jsonplaceholder.typicode.com/users/1");
const promise2 = fetch("https://jsonplaceholder.typicode.com/users/2");
const promise3 = fetch("https://jsonplaceholder.typicode.com/users/3");
Promise.all([promise1, promise2, promise3])
.then(function(results) {
console.log("all three done", results);
})
.catch(function(error) {
console.log("one of them failed:", error);
});
All three run at the same time. When all finish .then runs.
If even one fails .catch runs.
Much faster than doing them one by one.
A small complete example
<!DOCTYPE html>
<html>
<body>
<button id="loadBtn">Load User</button>
<p id="result">click the button</p>
<script>
const btn = document.getElementById("loadBtn");
const result = document.getElementById("result");
btn.addEventListener("click", async function() {
result.textContent = "loading...";
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
const data = await response.json();
result.textContent = "Name: " + data.name;
} catch (error) {
result.textContent = "something went wrong";
}
});
</script>
</body>
</html>
Click the button. It fetches a user from an API and shows the name.
Real async code working in the browser.
That is it honestly
Promises sound scary but the idea is simple. You ask for something,
you wait, either you get it or something goes wrong.
Start with fetch and async await. That is what you will use 90 percent
of the time anyway.
Top comments (0)