Logo

dev-resources.site

for different kinds of informations.

Why Wait? Exploring Asynchronous and Non-Blocking Programming 🚦

Published at
11/16/2024
Categories
javascript
programming
asynchronous
nonblockingio
Author
digvijay-bhakuni
Author
16 person written this
digvijay-bhakuni
open
Why Wait? Exploring Asynchronous and Non-Blocking Programming 🚦

If you've ever worked with code that juggles multiple tasks at the same time, you've probably come across the terms asynchronous and non-blocking. At first glance, they might seem like twins 👯‍♂️, but they are more like cousins. Let’s break it down in the simplest way possible, complete with examples and some fun emojis to keep things light!


🌟 The Basics

1️⃣ Asynchronous

  • What it means:

    Asynchronous programming is like telling your friend to bake a cake 🍰 while you clean the house 🏠. Both tasks happen in parallel, and you don't wait for your friend to finish before you start.

  • Key idea: Delegation and waiting for results later.

2️⃣ Non-Blocking

  • What it means:

    Non-blocking programming is like using a microwave to heat your food 🍲. Instead of waiting in front of the microwave while it works, you start folding laundry 🧺.

  • Key idea: No waiting around while something is being processed.


🔍 Breaking It Down

🚀 Asynchronous Programming Example

Imagine you're ordering pizza 🍕 while working on your computer 💻.

  1. You call the pizza place and place your order (start a task).
  2. While the pizza is being prepared and delivered, you continue working on your computer (you’re not sitting idle).
  3. The pizza delivery person rings the doorbell, and you pause to answer (handle the result of the task).

Here’s what it might look like in code using async/await:

async function orderPizza() {
    console.log("Placing order for pizza...");
    const pizza = await preparePizza(); // This takes time, but we don’t wait here.
    console.log("Pizza is ready: 🍕", pizza);
}

function preparePizza() {
    return new Promise((resolve) => {
        setTimeout(() => resolve("Delicious Pizza"), 3000); // Simulate a delay
    });
}

orderPizza();
console.log("Continuing to work on my project..."); // This runs immediately
Enter fullscreen mode Exit fullscreen mode

💡 Key Takeaway: Asynchronous means we can schedule tasks and be notified when they’re done, but our program doesn’t stop to wait.


🌀 Non-Blocking Programming Example

Now imagine you’re at a restaurant 🏮. You place your order, and the server doesn’t stop everything to prepare your dish 🍜. Instead, they move on to serve the next customer.

Here’s how that looks in Node.js with a non-blocking file read:

const fs = require('fs');

// Non-blocking file read
fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error("Error reading file:", err);
        return;
    }
    console.log("File content:", data);
});

console.log("I can keep doing other stuff while the file is being read...");
Enter fullscreen mode Exit fullscreen mode

💡 Key Takeaway: Non-blocking code doesn’t pause to wait for a task to finish—it moves on immediately.


🔄 Asynchronous vs Non-Blocking

Feature Asynchronous Non-Blocking
Core Concept Schedule tasks and get results later Perform tasks without pausing the program
Real-Life Analogy Ordering pizza while working Using a microwave and folding laundry
Programming Example async/await, promises, callbacks Event loops, non-blocking I/O
Wait for Result? Yes, but only when you need it No, just keep moving forward!

💡 When to Use What?

  • Use asynchronous programming when you need to run tasks concurrently but still want to process results later. Perfect for network requests, database queries, or background computations.
  • Use non-blocking code when you want to keep your program highly responsive, especially in I/O-heavy operations like reading files, handling API calls, or responding to multiple users.

🏁 Wrapping It Up

Asynchronous programming is about managing when tasks complete, while non-blocking programming is about not waiting for tasks to finish. Understanding the difference helps you build efficient, responsive apps that users ❤️.

So next time someone asks, you’ll know:

Asynchronous is about the future, and non-blocking is about the now! ⏳⚡

🚀 Happy coding!

asynchronous Article's
30 articles in total
Favicon
Why is My Multi-Threaded API Still Slow?
Favicon
Building Async APIs in ASP.NET Core - The Right Way
Favicon
Understanding Synchronous and Asynchronous Bus Timing
Favicon
Async Vs Sync, which is most preferrable?
Favicon
Mastering Asynchronous Programming in JavaScript
Favicon
Why Modern Programming Isn't Always Asynchronous (And That's Okay, Mostly)
Favicon
Zero-Cost Abstractions in Rust: Asynchronous Programming Without Breaking a Sweat
Favicon
Why Wait? Exploring Asynchronous and Non-Blocking Programming 🚦
Favicon
The Tale of Async, Multithread, and Parallel: Heroes of the .NET Realm
Favicon
Getting Started with Asynchronous Programming in Dart
Favicon
JavaScript Event Loop
Favicon
Asynchronous programming in Javascript
Favicon
This Week I Learnt: Java's CompletableFuture
Favicon
How to Run a Method Asynchronously in a Reactive Chain in Spring WebFlux?
Favicon
Programación asincrónica en Javascript
Favicon
Understanding the Event Loop, Callback Queue, and Call Stack & Micro Task Queue in JavaScript
Favicon
Mastering Callbacks in JavaScript 💻🔥
Favicon
Mastering Concurrency in C with Pthreads: A Comprehensive Guide
Favicon
Async/Await keeps order in JavaScript;
Favicon
Rate my python async snippet
Favicon
Returning a Promise — How an async function operates
Favicon
A Project of async springboot and react js from where i can learn please help...
Favicon
GPT teaches me how to make my logic sync and async at the same time with trampolines
Favicon
Understanding JavaScript Promises and Callbacks
Favicon
Pros and Cons of Event-Driven Architecture
Favicon
Asynchronous Communication with Apache Kafka
Favicon
Dig deeper into JavaScript.
Favicon
Is async/await a good idea? 🤔 async/await vs promises
Favicon
What is RabbitMQ and why do you need a Message Broker?
Favicon
🍳 Asynchronous Programming in C# Made Easy: Breakfast Included! ☕️

Featured ones: