In JavaScript, an asynchronous function is a function that returns a promise, which allows it to perform non-blocking operations such as making HTTP requests or reading and writing files without blocking the execution of the rest of the program.
The async function allows you to write asynchronous code that looks like synchronous code, which can make it easier to read and maintain.
Async functions were introduced in ECMAScript 2017 (ES8) as a way to simplify the use of promises and make it easier to write asynchronous code.
An async function is defined using the async
keyword before the function declaration or expression, like this:
async function getData() {
// Async code goes here
}
Inside an async function, you can use the await
keyword to pause the execution of the function until a promise is resolved. The await
keyword can only be used inside an async function.
Here’s an example that demonstrates how you might use an async function to fetch data from an API using the fetch
method:
async function getData() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
console.log(data);
}
In this example, the fetch
method is used to make an HTTP request to an API, and the await
keyword is used to pause the execution of the function until the response is received. The response.json()
method is also asynchronous and returns a promise, so the await
keyword is used again to pause the execution of the function until the data is parsed from the response.
Async functions can also be used with traditional callbacks or with other asynchronous functions.
Here’s an example that demonstrates how you might use an async function to read a file using the fs
module in Node.js:
const fs = require("fs");
async function readFile(path) {
try {
const data = await new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
console.log(data);
} catch (error) {
console.error(error);
}
}
readFile("./example.txt");
In this example, the readFile
function uses the fs.readFile
method to read the contents of a file. The fs.readFile
method takes a callback function that is called when the file is read. To use the fs.readFile
method with an async function, the callback function is wrapped in a promise that is awaited using the await
keyword. If an error occurs during the execution of the function, the catch
block is used to handle the error.
Async functions can also be used with the Promise.all
method to run multiple asynchronous operations in parallel.
Here’s an example that demonstrates how you might use an async function to fetch data from multiple APIs at once:
async function getCombinedData() {
const [userData, postComments] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/1").then((response) =>
response.json()
),
fetch("https://jsonplaceholder.typicode.com/posts/1/comments").then(
(response) => response.json()
),
]);
console.log(userData, postComments);
}
getCombinedData();
In this example, the Promise.all
method is used to execute two fetch
requests in parallel. The await
keyword is used to pause the execution of the function until both promises have resolved. The data from both requests is returned as an array, which is destructured into separate variables for easy access.
In addition to using the await
keyword, you can also use the async keyword with the for...of
loop to iterate over a collection of promises.
Here’s an example that demonstrates how you might use an async function to fetch data from multiple APIs using the for...of
loop:
async function getAllPosts() {
const postIds = [1, 2, 3, 4, 5];
const posts = [];
for (const postId of postIds) {
const post = await fetch(
`https://jsonplaceholder.typicode.com/posts/${postId}`
).then((response) => response.json());
posts.push(post);
}
console.log(posts);
}
getAllPosts();
In this example, the getAllPosts
function uses the for...of
loop to iterate over an array of post IDs. Inside the loop, the fetch
method is used to make a request to the API for each post ID. The await
keyword is used to pause the execution of the loop until the promise is resolved. The data for each post is then pushed onto an array, which is logged to the console after all promises have been resolved.
One important thing to keep in mind when using async functions is error handling. When an async function encounters an error, it will reject the promise and throw an exception. If the exception is not caught, it will cause the program to crash. To handle errors in async functions, you can use the try...catch
statement or the .catch()
method on the returned promise.
Here’s an example that demonstrates how you might handle errors in an async
function:
async function getUserData(userId) {
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
getUserData(1);
In this example, the try...catch
statement is used to handle errors that may occur while making a request to the API or parsing the response data. If an error occurs, the catch
block is executed, and the error is logged to the console.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.