JavaScript normally runs one piece of code after another. But some tasks take time, such as getting data from a server or waiting for a timer. Asynchronous JavaScript lets the program continue running while it waits for these tasks to finish.
Synchronous vs Asynchronous JavaScript
- Synchronous code runs one line at a time. The next line waits for the previous line to finish.
- Asynchronous code can start a task and continue running other code while waiting for that task to finish.
For example, setTimeout() can run code after a certain amount of time.
setTimeout()
setTimeout() runs a function after the given time. The time is written in milliseconds. 1000 milliseconds means 1 second.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript setTimeout</title>
</head>
<body>
<h1>setTimeout Example</h1>
<script>
console.log("Start");
setTimeout(function() {
console.log("This message appears after 2 seconds.");
}, 2000);
console.log("End");
</script>
</body>
</html>
Output:
Start
End
This message appears after 2 seconds.
The timer does not stop JavaScript from running the next line.
Callbacks
A callback function is a function that is given to another function so it can be called later.
You have already used this idea with methods such as forEach() and addEventListener().
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Callback</title>
</head>
<body>
<h1>Callback Example</h1>
<script>
function showMessage(name, callback) {
console.log("Hello " + name);
callback();
}
function finished() {
console.log("The task is finished.");
}
showMessage("Aman", finished);
</script>
</body>
</html>
Output:
Hello Aman
The task is finished.
Here, finished is passed to showMessage() and is called after the first message.
Promises
A Promise represents a task that will finish in the future. A Promise can be:
- Pending → still running
- Fulfilled → completed successfully
- Rejected → failed
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Promise</title>
</head>
<body>
<h1>Promise Example</h1>
<script>
let promise = new Promise(function(resolve, reject) {
resolve("Task completed!");
});
promise.then(function(result) {
console.log(result);
});
</script>
</body>
</html>
Output:
Task completed!
resolve()means the task was successful.
reject()is used when the task fails.
- The
.then()method runs when the Promise is successfully completed.
async and await
async and await make Promise-based code easier to read.
- An
asyncfunction always returns a Promise.
awaitwaits for a Promise to finish before moving to the next line inside the function.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Async Await</title>
</head>
<body>
<h1>async and await</h1>
<script>
function getMessage() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve("Data received!");
}, 2000);
});
}
async function showMessage() {
console.log("Waiting...");
let message = await getMessage();
console.log(message);
}
showMessage();
</script>
</body>
</html>
Output:
Waiting...
Data received!
The second message appears after 2 seconds.
Fetch API
The Fetch API is used to request data from a server. It returns a Promise, so you can use .then() or async and await with it.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Fetch API</title>
</head>
<body>
<h1>Fetch API Example</h1>
<script>
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log("Error:", error);
});
</script>
</body>
</html>
Example output:
{
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit..."
}
The exact console formatting can be different depending on the browser. fetch() requests the data, response.json() converts the response into JavaScript data, and the second .then() receives that data.
Working with APIs
An API allows one application to communicate with another application and exchange data. For example, a website can use an API to get:
- User information
- Product details
- Weather data
- News
- Posts and comments
Most APIs return data in JSON format, which makes it easy for JavaScript to work with the information. A common pattern is:
fetch("API_URL")
.then(response => response.json())
.then(data => {
console.log(data);
});
You will use this pattern often when working with real websites and applications.
Key Points
- Asynchronous code allows JavaScript to handle tasks that take time.
setTimeout()runs code after a delay.- A callback is a function passed to another function.
- Promises represent tasks that finish in the future.
asyncandawaitmake Promise-based code easier to write.fetch()is used to get data from APIs.- APIs allow applications to exchange data, often using JSON.
Frequently Asked Questions (FAQs)
Q1. What is Asynchronous JavaScript?
Asynchronous JavaScript allows tasks that take time, such as timers and server requests, to run without stopping the rest of the program. This helps web applications remain responsive while waiting for a task to finish.
Q2. What are JavaScript Promises?
JavaScript Promises represent the result of an asynchronous task. A Promise can be pending, fulfilled, or rejected depending on whether the task is still running, completed successfully, or failed.
Q3. How do JavaScript Async Await work?
JavaScript Async Await provides a simpler way to work with Promises. An async function returns a Promise, while await pauses the function until the Promise is completed.
Q4. What are JavaScript Callbacks?
JavaScript Callbacks are functions passed to another function to be called later. They are commonly used with asynchronous operations, event listeners, timers, and array methods.
Q5. What is the JavaScript Fetch API used for?
The JavaScript Fetch API is used to request data from a server or API. It returns a Promise and can be used with .then() and .catch() or with async and await.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
