In the previous article, we learned about ES6 features. Modern JavaScript applications often need to perform tasks that take time, such as:
Loading data from a server
Downloading files
Fetching weather information
Processing payments
Uploading images
If JavaScript waited for each task to finish before doing anything else, websites would become slow and unresponsive.
To solve this problem, JavaScript uses Asynchronous Programming.
In this article, we will learn:
Synchronous Programming
Asynchronous Programming
Callbacks
Callback Hell
Promises
Promise States
Async/Await
Fetch API
Error Handling
Real-world Examples
What is Synchronous Programming?
In synchronous programming, statements execute one after another in sequence.
Example:
console.log("Start");
console.log("Middle");
console.log("End");
Output:
Start
Middle
End
Execution follows the order of code.
How Synchronous Execution Works
Line 1
↓
Line 2
↓
Line 3
Each statement waits for the previous one.
Problem with Synchronous Programming
Imagine downloading a large file.
Download File
Wait...
Wait...
Wait...
The entire application becomes blocked.
What is Asynchronous Programming?
Asynchronous programming allows JavaScript to continue executing other code while waiting for long-running tasks to complete.
Example:
Start Download
Continue Other Work
Download Completes Later
Real-Life Example
Suppose you order food.
Synchronous:
Order Food
Wait at Counter
Food Ready
Go Home
Asynchronous:
Order Food
Sit with Friends
Food Ready
Collect Food
More efficient.
Example Using setTimeout()
console.log("Start");
setTimeout(
function()
{
console.log("Delayed");
},
2000
);
console.log("End");
Output
Start
End
Delayed
Dry Run
Start Printed
↓
Timer Started
↓
End Printed
↓
2 Seconds Later
↓
Delayed Printed
What is a Callback Function?
A callback is a function passed as an argument to another function.
Example
function greet(name)
{
console.log(
"Hello " + name
);
}
function processUser(
callback
)
{
callback("Rahul");
}
processUser(greet);
Output
Hello Rahul
Why Callbacks Are Used
Callbacks help execute code after a task completes.
Example:
Download File
↓
Run Callback
Asynchronous Callback Example
setTimeout(
function()
{
console.log(
"Task Completed"
);
},
3000
);
Output after 3 seconds:
Task Completed
Callback Hell
When callbacks are nested deeply, code becomes difficult to read.
Example:
task1(
function()
{
task2(
function()
{
task3(
function()
{
task4(
function()
{
}
);
}
);
}
);
}
);
Problem
Too Many Nested Functions
This is called:
Callback Hell
or
Pyramid of Doom
Solution: Promises
Promises were introduced to solve callback hell.
What is a Promise?
A Promise represents a value that may be available now, later, or never.
Example:
Food Ordered
↓
Promise Created
↓
Food Delivered
Promise States
A promise has three states.
Pending
↓
Fulfilled
or
Rejected
Pending
Operation is running.
Fulfilled
Operation completed successfully.
Rejected
Operation failed.
Creating a Promise
Syntax:
let promise =
new Promise(
function(resolve,reject)
{
}
);
Example
let promise =
new Promise(
function(resolve,reject)
{
resolve(
"Success"
);
}
);
Consuming a Promise
Using .then().
Example:
promise.then(
function(result)
{
console.log(result);
}
);
Output:
Success
Promise Example
let promise =
new Promise(
function(resolve,reject)
{
let success = true;
if(success)
{
resolve(
"Operation Successful"
);
}
else
{
reject(
"Operation Failed"
);
}
}
);
promise
.then(
function(result)
{
console.log(result);
}
)
.catch(
function(error)
{
console.log(error);
}
);
Output
Operation Successful
Promise Chain
Example:
Promise.resolve(5)
.then(
num => num*2
)
.then(
num => num+10
)
.then(
result =>
console.log(result)
);
Output:
20
Async and Await
Introduced in ES8.
Makes asynchronous code look synchronous.
Without Async/Await
promise
.then(
result =>
{
}
)
.catch(
error =>
{
}
);
With Async/Await
async function demo()
{
let result =
await promise;
}
Cleaner and easier to read.
async Keyword
Declares an asynchronous function.
Example:
async function greet()
{
return "Hello";
}
Output
Returns a Promise.
await Keyword
Pauses execution until a promise completes.
Example:
let result =
await promise;
Example
function fetchData()
{
return new Promise(
function(resolve)
{
setTimeout(
function()
{
resolve(
"Data Received"
);
},
2000
);
}
);
}
Using Async/Await
async function show()
{
let result =
await fetchData();
console.log(result);
}
show();
Output after 2 seconds:
Data Received
Dry Run
show()
↓
await fetchData()
↓
Wait 2 Seconds
↓
Data Received
↓
Print Result
Error Handling
Using try-catch.
Example:
async function test()
{
try
{
let result =
await promise;
console.log(result);
}
catch(error)
{
console.log(error);
}
}
What is Fetch API?
Fetch API is used to make HTTP requests.
It is the modern replacement for XMLHttpRequest.
Uses of Fetch API
Get data from servers
Call APIs
Send data
Upload files
Basic Fetch Syntax
fetch(url)
.then(
response =>
response.json()
)
.then(
data =>
console.log(data)
);
Example
fetch(
"https://jsonplaceholder.typicode.com/users"
)
.then(
response =>
response.json()
)
.then(
data =>
console.log(data)
);
How Fetch Works
Request Sent
↓
Server Responds
↓
JSON Data Returned
↓
Display Data
Fetch with Async/Await
async function getUsers()
{
let response =
await fetch(
"https://jsonplaceholder.typicode.com/users"
);
let data =
await response.json();
console.log(data);
}
getUsers();
Fetch Error Handling
async function getData()
{
try
{
let response =
await fetch(url);
let data =
await response.json();
console.log(data);
}
catch(error)
{
console.log(
error
);
}
}
Practical Example – Fake User Data
async function getUser()
{
let response =
await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
let data =
await response.json();
console.log(
data.name
);
}
getUser();
Output:
Leanne Graham
Complete Program
<!DOCTYPE html>
<html>
<body>
<script>
async function getData()
{
let response =
await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
let data =
await response.json();
console.log(data);
}
getData();
</script>
</body>
</html>
Synchronous vs Asynchronous
| Synchronous | Asynchronous |
|---|---|
| One task at a time | Multiple tasks |
| Blocking | Non-blocking |
| Slower for long tasks | Faster and efficient |
Callbacks vs Promises vs Async/Await
| Feature | Callback | Promise | Async/Await |
|---|---|---|---|
| Readability | Low | Medium | High |
| Callback Hell | Yes | No | No |
| Error Handling | Difficult | Better | Best |
Real-Life Applications
Asynchronous programming is used in:
Chat applications
Weather apps
Online shopping
Banking systems
Video streaming
Social media platforms
Services like Netflix, YouTube, and Amazon rely heavily on asynchronous operations.
Common Mistakes Beginners Make
Forgetting await
Wrong:
let data =
fetch(url);
Correct:
let data =
await fetch(url);
Missing async
Wrong:
function getData()
{
await fetch(url);
}
Correct:
async function getData()
{
await fetch(url);
}
Ignoring Errors
Always use:
try-catch
or
.catch()
Advantages of Asynchronous Programming
Faster applications
Better user experience
Efficient resource usage
Handles multiple tasks simultaneously
Essential for modern web development
Conclusion
Asynchronous programming is one of the most important concepts in modern JavaScript. It allows applications to communicate with servers, fetch data, and perform long-running operations without freezing the user interface.
Comments
Post a Comment