In JavaScript, some operations take time to complete, such as fetching data from an API or waiting for a timer.
Asynchronous JavaScript allows JavaScript to handle these operations without blocking other work.
Let's understand it with simple examples!
1. Synchronous JavaScript
Synchronous code runs one line at a time, in order.
console.log("First");
console.log("Second");
console.log("Third");
Output:
First
Second
Third
Each statement runs before the next one.
2. Asynchronous JavaScript
Asynchronous operations allow JavaScript to continue other work while waiting for an operation to finish.
console.log("First");
setTimeout(() => {
console.log("Second");
}, 2000);
console.log("Third");
Output:
First
Third
Second
Why?
-
"First"prints immediately. -
setTimeout()schedules the callback to run after approximately two seconds. -
"Third"prints without waiting for the timer. -
"Second"prints when the timer finishes and its callback can run.
This is a simple example of asynchronous JavaScript.
3. Where Do We Use Asynchronous JavaScript?
Asynchronous JavaScript is commonly used for:
- Fetching data from APIs.
- Loading products in an e-commerce website.
- Sending login details to a server.
- Uploading files.
- Communicating with databases through a backend.
For example, we can fetch products from an API:
fetch("https://fakestoreapi.com/products")
.then((response) => response.json())
.then((products) => {
console.log(products);
})
.catch((error) => {
console.log("Error:", error);
});
Top comments (0)