What is a Promise?
A Promise is just a way for JavaScript to handle asynchronous operations - things that take time
like:
- Fetching data from a server
- Reading a file
- Waiting for a timeout Instead of blocking everything, JavaScript says: "Hey! I'll do this task, and when I'm done, I'll let you know." A Promise can be in 3 states:
- Pending - task is not done yet
- Resolved - task completed successfully
- Rejected - task failed
Basic Syntax of a Promise
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task done!");
} else {
reject("Something went wrong.");
}
});
promise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
Real Example: Fake API Call
function fakeAPICall() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received!");
}, 2000);
});
}
fakeAPICall()
.then(data => console.log(data))
.catch(err => console.log(err));
Output after 2 seconds: Data received!
Chaining Promises
doSomething()
.then(result1 => doSomethingElse(result1))
.then(result2 => doMore(result2))
.catch(error => console.log(error));
My Personal Tip
Think of them like a food delivery app:
- You order (async task starts)
- You get food (resolve)
- Or delivery fails (reject) And .then() is what you do when food arrives
Resources That Helped Me
- MDN Web Docs - Promises
- JavaScript.info - Promises
Final Thoughts
At first, I used to avoid Promises. But once I started coding with real APIs in React, I had to learn
them - and I'm glad I did.
If you're new to Promises, I hope this helped you simplify the concept!
Drop a comment if you found this helpful or if you want me to write about async/await next!
Thanks for reading!
Follow me on Dev.to - this is just the start of my blog journey
Top comments (2)
Heres another tip:
When you order from different food deliveries for food event and you need to serve them when all arrive
Dislaimer: do not copy this code ... it's for reference only !
pretty cool seeing you stick with stuff that’s tough at first. you ever feel like it’s all about just showing up every day till it finally clicks?