Hello, fellow developers! Today, lets unravel the mysteries of asynchronous JavaScript by immersing ourselves in the dynamic world of a bustling coffee shop. Get ready to explore the concepts of callbacks, promises, and the magic of async/awaitall while sipping on a freshly brewed cup of coffee. ๐
Understanding Asynchronous JavaScript ๐คน๐ป
If youre looking to boost project efficiency, asynchronous JavaScript is your secret weapon. It allows you to break down intricate projects into manageable tasks. In this journey, well delve into three techniquescallbacks, promises, and async/awaitto conquer these tasks and achieve optimal results. Lets dive right in! ๐
Synchronous vs Asynchronous JavaScript ๐
Synchronous System : Imagine having just one hand to complete multiple tasksone at a time. JavaScript, by default, is synchronous (single-threaded). Tasks wait for the previous one to finish.
Asynchronous System : Picture having multiple hands, each completing a task independently. In JavaScript, this asynchronous system enables tasks to proceed concurrently. No task waits for another, creating a more efficient workflow.
Synchronous Code Example :
console.log("Sip");
console.log("Enjoy");
console.log("Repeat");
Asynchronous Code Example :
console.log("Sip");
// This will be shown after 2 seconds
setTimeout(() => {
console.log("Enjoy");
}, 2000);
console.log("Repeat");
Now that weve grasped the basics, lets step into our coffee shop project and explore the magic of callbacks.
Setting Up Our Coffee Shop Project
For this project, open your preferred code editor or Codepen.io. Well use the console to witness our coffee shop in action.
Callbacks in JavaScript ๐ฒ
Callbacks come into play when you nest a function inside another function as an argument. Imagine a callback as taking smaller steps to complete a complex task. To illustrate, lets start our coffee shop business with a storeroom for ingredients and a kitchen for production.
let supplies = {
Beans: ["Arabica", "Robusta", "Liberica"],
Liquid: ["water", "milk", "syrup"],
Cups: ["small", "medium", "large"],
Toppings: ["cinnamon", "chocolate"]
};
let order = (beanType, callBrew) => {
console.log("Order placed. Please call brewing process");
callBrew();
};
let brew = () => {
console.log("Brewing process initiated");
};
// Test our setup
order("Arabica", brew);
With callbacks, we establish relationships between steps, crucial for tasks like serving the perfect cup of coffee. As we delve deeper into the project, the order of tasks becomes paramount.
The Challenge: Callback Hell ๐ฑ
Nested callbacks can lead to a messy structure known as Callback Hell. It becomes challenging to maintain and understand the code. Fear not; theres a hero on the horizonpromises!
Escaping Callback Hell with Promises ๐ ๐ป
Promises were introduced to rescue us from the clutches of Callback Hell. They offer a cleaner structure and better task handling.
let order = (time, work) => {
return new Promise((resolve, reject) => {
if (isShopOpen) {
setTimeout(() => {
console.log(`${supplies.Beans[beanType]} was selected`);
resolve(work());
}, time);
} else {
reject(console.log("Our shop is closed"));
}
});
};
// Usage example
order(2000, () => console.log("Brewing process initiated"))
.then(() => order(1000, () => console.log("Liquid added")))
.then(() => order(2000, () => console.log("Machine started")))
.catch(() => console.log("Customer left"))
.finally(() => console.log("End of the day"));
With promises, we chain tasks using .then()
, making the code more readable. But wait, theres more magic to explorethe enchanting Async/Await duo!
Embracing Simplicity with Async/Await ๐
Async/Await simplifies asynchronous JavaScript further. By labeling a function as async
, it becomes a promise, and the await
keyword pauses execution until the promise is resolved.
async function coffeeShop() {
try {
await order(2000, () => console.log(`${supplies.Beans[0]} was selected`));
await order(1000, () => console.log("Brewing process initiated"));
await order(2000, () => console.log("Liquid added"));
await order(1000, () => console.log("Start the machine"));
await order(2000, () => console.log(`Coffee served in ${supplies.Cups[1]} cup`));
await order(3000, () => console.log(`${supplies.Toppings[0]} sprinkled on top`));
await order(2000, () => console.log("Enjoy your coffee"));
} catch (error) {
console.log("Customer left", error);
} finally {
console.log("Coffee shop closed for the day");
}
}
// Trigger the coffee shop
coffeeShop();
In our coffee shop journey, weve explored the nuances of synchronous and asynchronous JavaScript, battled Callback Hell with promises, and embraced the elegance of Async/Await. Now, armed with these tools, venture forth into the vast world of asynchronous programming! May your code flow like a perfectly brewed cup of coffee. ๐
Connect with Me on social media ๐ฒ
๐ฆ Follow me on Twitter: devangtomar7
๐ Connect with me on LinkedIn: devangtomar
๐ท Check out my Instagram: be_ayushmann
Checkout my blogs on Medium: Devang Tomar
# Checkout my blogs on Hashnode: devangtomar
๐ง๐ป Checkout my blogs on Dev.to: devangtomar
Top comments (0)