Hey there, JavaScript enthusiasts! π Are you ready to dive into Promises and make your async code cleaner and more fun? π Letβs break it down step-by-step with simple examples, fewer boring theories, and loads of practical code snippets! π»β¨
Whatβs a Promise? π€
A Promise in JavaScript is like a "promise" in real life:
- Pending: "I'll do this later."
- Fulfilled: "I did it!" π
- Rejected: "Oops, something went wrong." π’
Why Use Promises? πββοΈ
Before Promises, we had callbacks, which often led to callback hell:
getData(function (data) {
processData(data, function (result) {
saveData(result, function (response) {
console.log("All done!");
});
});
});
π΅ Hard to read, right?
Promises save the day! π¦ΈββοΈ They flatten this mess into a chain:
getData()
.then(processData)
.then(saveData)
.then(() => console.log("All done!"))
.catch((error) => console.error("Something went wrong:", error));
Let's Build a Promise π
Hereβs how you create a promise:
const myPromise = new Promise((resolve, reject) => {
const success = true; // Change this to false to see rejection
if (success) {
resolve("Yay! It worked! π");
} else {
reject("Oh no! Something went wrong. π’");
}
});
Using the promise:
myPromise
.then((message) => console.log(message))
.catch((error) => console.error(error));
Real-Life Example: Fetching Data π
Promises are everywhere in JavaScript! A common one is fetch
.
Letβs get some user data:
fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json()) // Convert response to JSON
.then((data) => console.log("User data:", data)) // Log the data
.catch((error) => console.error("Error fetching data:", error)); // Handle errors
Chaining Promises π
You can chain .then
for multiple steps:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((post) => {
console.log("Post Title:", post.title);
return fetch(`https://jsonplaceholder.typicode.com/users/${post.userId}`);
})
.then((response) => response.json())
.then((user) => console.log("Author:", user.name))
.catch((error) => console.error("Something went wrong:", error));
Handling Errors π
The .catch
block handles any error in the chain:
fetch("https://jagroopurl.com") // BTW This doesn't exist
.then((response) => response.json())
.catch((error) => console.error("Oops, error caught here:", error));
Pro tip: Add a .catch
at the end of every chain to avoid unhandled errors. π¨
Parallel Promises with Promise.all
π
Run multiple promises in parallel:
const promise1 = fetch("https://jsonplaceholder.typicode.com/posts/1");
const promise2 = fetch("https://jsonplaceholder.typicode.com/posts/2");
Promise.all([promise1, promise2])
.then((responses) => Promise.all(responses.map((r) => r.json())))
.then((data) => console.log("Both posts:", data))
.catch((error) => console.error("One or more promises failed:", error));
A Promise-Based Timer β³
Let's create a timer using promises:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(2000).then(() => console.log("2 seconds later... β°"));
Let's Test Your Knowledge! π§
Hereβs a tricky question for you:
const promise = new Promise((resolve, reject) => {
console.log("1. Promise created");
resolve("2. Promise resolved");
});
promise.then((msg) => console.log(msg));
console.log("3. Synchronous log");
What will be the output? π€
Your Turn! π€
Did this make Promises less intimidating? π Try out the examples, tweak them, and share your answers to the tricky question in the comments below! π
Happy coding! π
Top comments (5)
great, thanks for sharing .
You're welcome! π
log:
1
3
2
Thanks for the nice article π
Absolutely correct !! @_aliraza ,
I hope you know the reason for this.
I would also add that while using promise.all could speedup things, it still runs in the same thread, many people don't realize this and end up wondering why their code is slow.