1. Definitions
Synchronous: Tasks execute sequentially, one after another. Each task waits for the previous one to complete before starting.
Asynchronous: Tasks execute independently. The program doesn’t wait for a task to finish before moving to the next one. Results are handled later (e.g., via callbacks or promises).
2. Key Differences
Synchronous | Asynchronous |
---|---|
Blocking (program waits) | Non-blocking (program continues) |
Ordered execution | Unordered or parallel execution |
Simpler to reason about | More complex due to callbacks/promises |
Example: Reading files one by one | Example: Fetching data from an API |
3. Real-World Examples
Synchronous:
A coffee shop where you wait in line, place your order, and wait until your coffee is ready before the next customer is served.Asynchronous:
Ordering food online: you submit your request, do other tasks, and get a notification when the food arrives.
4. Code Examples
Synchronous (JavaScript)
console.log("Start"); function syncTask() { for (let i = 0; i < 1e9; i++) {} // Simulate a long task } syncTask(); // Blocks the next line until done console.log("End");
Output:
Start End (after a long delay)
Asynchronous (JavaScript)
console.log("Start"); setTimeout(() => console.log("Async Task Done"), 2000); // Non-blocking console.log("End");
Output:
Start End Async Task Done (after 2 seconds)
5. When to Use Which?
Synchronous:
Use for simple, linear tasks (e.g., scripts that require order, like calculating results step-by-step).Asynchronous:
Use for I/O operations (e.g., API calls, file uploads) or tasks that could block the UI (e.g., in web apps).
Summary
Synchronous = “Wait in line” (blocking).
Asynchronous = “Take a ticket and do other things” (non-blocking).
No comments:
Post a Comment