"JavaScript Kitchen Nightmares: How to Cook Up Callbacks, Promises, and Async/Await Without Burning the Code"
Let's imagine you're organizing a dinner party and you need to prepare several dishes. In this scenario, cooking represents performing tasks in JavaScript, and you have three different ways to manage these tasks: callbacks, promises, and async/await.
Callbacks:
Imagine you have a helper, but they're not very reliable. You ask them to start making a salad, but instead of telling you when it's ready, they just shout from the kitchen when they're done. You have to be paying attention to their shout to know when the salad is ready, and then you can start serving it.
- Real-life scenario: This is like using a callback. You pass a function (the shout) that gets called when the task is complete. It works, but it can get messy, especially if you have many tasks (dishes) happening at the same time and you're trying to keep track of them all.
function cookDish(dishName, callback) {
console.log(`Starting to cook ${dishName}...`);
setTimeout(() => {
console.log(`${dishName} is ready!`);
callback(); // Notify that the dish is ready
}, 2000); // Simulating 2 seconds cooking time
}
// Usage
cookDish('Pasta', () => {
console.log('Callback: Serve the pasta.');
});
Promises:
Now, imagine you ask a more dependable helper to make a salad. They promise you that they'll either finish it (fulfill the promise) or tell you if something goes wrong (reject the promise). You can choose what to do once the promise is fulfilled or rejected, like serving the salad or making something else if it fails.
- Real-life scenario: This is like using promises. A promise is an assurance that a task will complete in the future, and you can decide what to do next using .then() for success or .catch() for failure. It's easier to manage than callbacks, especially when dealing with multiple tasks.
领英推è
function cookDish(dishName) {
console.log(`Starting to cook ${dishName}...`);
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`${dishName} is ready!`);
resolve(); // Resolve the promise when the dish is ready
}, 2000); // Simulating 2 seconds cooking time
});
}
// Usage
cookDish('Pasta')
.then(() => {
console.log('Promise: Serve the pasta.');
});
Async/Await:
Finally, imagine you decide to make the salad yourself, but you want to do it in a way that allows you to still be present at the party. You start the salad, and while you're chopping vegetables, you tell everyone you'll be right back. Once the salad is ready, you finish it and return to the party without anyone noticing you were gone.
- Real-life scenario: This is like using async/await. You write your code as if it's synchronous (doing the task directly), but under the hood, it's still asynchronous, meaning you don't block the event loop. It's the cleanest and most readable way to manage asynchronous tasks, allowing you to wait for tasks to complete (await) without having to write extra .then() or callback functions.
function cookDish(dishName) {
console.log(`Starting to cook ${dishName}...`);
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`${dishName} is ready!`);
resolve(); // Resolve the promise when the dish is ready
}, 2000); // Simulating 2 seconds cooking time
});
}
// Usage with async/await
async function prepareDinner() {
await cookDish('Pasta');
console.log('Async/Await: Serve the pasta.');
}
prepareDinner();
Summary:
- Callbacks: Use when you have simple, one-off asynchronous tasks, but be cautious as it can get messy with multiple tasks (callback hell).
- Promises: Use when you need to manage asynchronous tasks more elegantly, especially when you have multiple tasks to chain together.
- Async/Await: Use when you want the clearest, most readable code for handling asynchronous tasks, especially in complex applications.
In a dinner party analogy, async/await is like being a smooth host who handles everything seamlessly, while promises are your reliable helpers, and callbacks are the loud but less coordinated ones.
GO Back-End developer | Student at Ajay Kumar Garg Engineering College
7 个月Well expalined
Backend Developer @Zoniqx | Canva | Top 0.32%: 288th/90K+ PrepSAT @PrepInsta | Represented IT Department at Silver Jubilee Project Exhibition 2023 @AKGEC
7 个月Must say, well explained Sanskar Gupta
Backend Developer
7 个月Very informative ??
Frontend Developer | Competitive Programmer
7 个月Very interesting..??