JavaScript is single-threaded, meaning it runs one operation at a time. However, we often need to perform tasks like API requests, file reading, or timers that take time to complete — this is where asynchronous JavaScript comes in.
1. What is Asynchronous Programming?
Asynchronous code allows tasks to run in the background without blocking the main thread. This helps in creating smooth, non-blocking user experiences (e.g., loading data from a server without freezing the page).
2. Synchronous vs Asynchronous
// Synchronous: Executes line by line
console.log("Start");
alert("Blocking alert box");
console.log("End");
// Asynchronous (non-blocking)
console.log("Start");
setTimeout(() => {
console.log("Inside setTimeout");
}, 1000);
console.log("End");
3. setTimeout() and setInterval()
- setTimeout(callback, delay) – runs the callback once after delay (ms)
- setInterval(callback, delay) – runs repeatedly every delay milliseconds
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
let count = 0;
const intervalId = setInterval(() => {
console.log("Count:", ++count);
if (count === 5) clearInterval(intervalId);
}, 1000);
4. Callbacks
A callback is a function passed as an argument to another function to be executed later.
function fetchData(callback) {
setTimeout(() => {
console.log("Data fetched");
callback();
}, 1000);
}
fetchData(() => {
console.log("Callback executed");
});
Problem: Callbacks can become hard to manage, leading to "callback hell".
5. Promises
A Promise represents a value that may be available now, later, or never.
const promise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
success ? resolve("Success!") : reject("Error!");
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));
.then()
– handles resolved promise.catch()
– handles errors.finally()
– runs regardless of success/failure
6. Async/Await
async
and await
make working with promises easier, using synchronous-looking code.
function getData() {
return new Promise((resolve) => {
setTimeout(() => resolve("Here is your data!"), 1000);
});
}
async function showData() {
console.log("Fetching...");
const result = await getData();
console.log(result);
}
showData();
- async – turns a function into a Promise
- await – pauses execution until the Promise settles
7. Fetch API
Used to make HTTP requests to servers. Returns a Promise.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Using async/await with fetch
async function loadPost() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await res.json();
console.log(data);
} catch (err) {
console.error("Error:", err);
}
}
loadPost();
8. Real-Life Use Cases
- Fetching data from APIs (AJAX)
- Reading/writing files (Node.js)
- Set timeout-based animations or transitions
- Handling user interactions/events asynchronously
Asynchronous JavaScript Quiz
1. What will be the output of the following code?
setTimeout(() => {
console.log('Hello');
}, 2000);
2. Which method is used to handle the resolved value of a Promise?
3. What is returned by an async function in JavaScript?
4. What will be the output of this code?
async function greet() {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Hello');
}
greet();
5. Which method is used to handle errors in a Promise?
6. Why is async/await often preferred over using plain Promises?
7. How can errors in async/await code be handled?
8. Which Promise method executes after both resolve and reject cases?
9. What is the purpose of 'resolve' in a Promise constructor function?
10. Where can the 'await' keyword be used?
11. What is a callback function in JavaScript?
12. When is the 'then' method of a Promise called?
13. What does the 'async' keyword do in front of a function?
14. What does 'Promise.all()' do?
15. What does 'Promise.race()' do?
16. When does the 'finally' method of a Promise execute?
17. What is a benefit of using 'async/await' in JavaScript?
18. What does 'Promise.reject()' do?
19. How can you handle errors in an 'async/await' function?
20. What does the 'await' keyword do?