Have you ever sat by the phone, waiting for a message from a friend? In the world of programming, waiting is a common thing too.
JavaScript Promises are like a pinky swear between you and your computer. They help you handle things that might take some time, like waiting for that call. In this post, we’ll explore Promises in easy-to-understand words, just like talking to a friend.
What is a JavaScript Promise?
A JavaScript Promise is like a handshake agreement between you and your computer. It’s a way to say, ‘I’ll get this information for you, just wait a moment.’ If everything goes well, you get what you need. If there’s a problem, it lets you know what went wrong.
How Does a Promise Work?
Pending: When you first create a JavaScript Promise, it’s in the ‘pending’ state. This means it’s still working on getting the result.
Fulfilled: When the task is done, the Promise is ‘fulfilled’. You get the result!
Rejected: If something goes wrong, the Promise is ‘rejected’. This means there was a problem.
Why Promises Matter:
Clean Code: Without JavaScript Promises, handling asynchronous tasks (things that take time) can get messy. Promises keep your code neat.
Better Flow Control: Promises let you plan what should happen if everything goes right, and what to do if something goes wrong.
Parallel Execution: You can set multiple Promises in motion simultaneously, and take action once all have completed. It’s like cooking several dishes at once, then serving them all together.
Error Handling with Multiple Catch Blocks:
Think about making a sandwich. Different issues can pop up: maybe you’re out of mayo, or the bread is moldy. Each snag needs its own solution.
JavaScript lets you use several ‘catch’ blocks to tackle various kinds of mistakes. It’s like having a unique backup plan for each issue that comes up when making your sandwich.
fetchData()
.then(data => processData(data))
.catch(TypeError, error => {
console.log('Type Error:', error);
})
.catch(error => {
console.log('General Error:', error);
});Promise.all and Promise.race:
Think of it like cooking a pizza and a pie simultaneously. You’d want both to be completely cooked before you start eating. This is what Promise.all is for; it ensures that all tasks are done before moving on.
Promise.all([fetchData(), getUser(), getComments()])
.then(results => {
// Do something with all the results
});Now, consider Promise.race as a sprint between two friends. In programming, Promise.race is like a sprint between two pals. The first one to reach the end is your champion! It lets you know which operation got done before the others.
Promise.race([fetchData1(), fetchData2()])
.then(result => {
// The result of the fastest Promise
});Promisify Functions:
Sometimes, you find old code that’s hard to use with new, shiny JavaScript Promises. Don’t worry! You can wrap this old code in a Promise blanket to make it feel like new.
It’s like taking an old toy and giving it a fresh coat of paint. This trick is called “Promisifying,” and it lets you use that old code just like you would use a Promise!
function promisify(oldFunction) {
return function(...args) {
return new Promise((resolve, reject) => {
oldFunction(...args, (error, result) => {
if (error) reject(error);
else resolve(result);
});
});
};
}Promise.allSettled:
Imagine you asked three friends to do chores: wash dishes, clean the room, and take out the trash. You want to know how they all did, even if some couldn’t finish their chores.
Promise.allSettled is like waiting for all your friends to report back, no matter if they succeeded or failed.
In this manner, you gain a complete understanding, enabling you to strategize your next steps.
Promise.allSettled([fetchData(), getUser(), getComments()])
.then(results => {
// Results of all Promises, fulfilled or rejected
});Conclusion:
JavaScript Promises are like making a deal with your computer. They help you run tasks that might take a bit of time, like downloading a picture or getting info from a website.
By understanding Promises, you make your code smarter and your life easier. Think of it like cooking: the better you plan, the tastier the meal. So continue to explore Promises and you’ll enhance your coding skills!


