JavaScript Essentials - Async/Await
Using async/await for asynchronous operations
Async/await is a modern way to handle asynchronous operations in JavaScript, built on top of Promises. This tutorial covers the basics of using async/await, including how to define async functions, use the await keyword, and handle errors.
Key Points:
- Async/await provides a more readable and convenient syntax for working with asynchronous code.
- Async functions return a Promise.
- The await keyword pauses the execution of an async function until a Promise is resolved.
Defining Async Functions
An async function is defined using the async
keyword before the function declaration. Async functions always return a Promise. Here is an example:
async function fetchData() {
return 'Data fetched';
}
fetchData().then(result => {
console.log(result); // Output: Data fetched
});
Using the Await Keyword
The await
keyword can be used inside an async function to pause execution until a Promise is resolved. Here is an example:
async function fetchData() {
const data = await new Promise((resolve, reject) => {
setTimeout(() => resolve('Data fetched'), 2000);
});
console.log(data); // Output: Data fetched
}
fetchData();
Error Handling with Async/Await
Error handling in async functions can be done using try/catch blocks. Here is an example:
async function fetchData() {
try {
const data = await new Promise((resolve, reject) => {
setTimeout(() => reject('Error fetching data'), 2000);
});
console.log(data);
} catch (error) {
console.error(error); // Output: Error fetching data
}
}
fetchData();
Chaining Async Functions
Multiple async functions can be chained together to perform sequential asynchronous operations. Here is an example:
async function firstTask() {
return await new Promise((resolve, reject) => {
setTimeout(() => resolve('First task completed'), 1000);
});
}
async function secondTask() {
return await new Promise((resolve, reject) => {
setTimeout(() => resolve('Second task completed'), 1000);
});
}
async function thirdTask() {
return await new Promise((resolve, reject) => {
setTimeout(() => resolve('Third task completed'), 1000);
});
}
async function performTasks() {
const first = await firstTask();
console.log(first); // Output: First task completed
const second = await secondTask();
console.log(second); // Output: Second task completed
const third = await thirdTask();
console.log(third); // Output: Third task completed
console.log('All tasks completed');
}
performTasks();
Using Async/Await with Fetch API
Here is an example of using async/await with the Fetch API to retrieve data from a remote server:
async function fetchUserData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching user data:', error);
}
}
fetchUserData();
Summary
In this tutorial, you learned about using async/await for asynchronous operations in JavaScript. You explored how to define async functions, use the await keyword, handle errors, chain async functions, and use async/await with the Fetch API. Understanding async/await is essential for writing modern, efficient, and readable asynchronous code in JavaScript.