JavaScript Async/Await: Writing Clean and Efficient Asynchronous Code
JavaScript is a single-threaded programming language. Thus, it means that it can execute one command at a time. How can this be possible? Well, the answer lies in the fact that JavaScript has something called asynchronous programming. It enables the execution of other code in the program while waiting for the result of those long operations.
👉 Download Javascript: from ES2015 to ES2023 - eBook
Primer on async/await
Async/await is one of the modern ways to handle asynchronous operations in JavaScript. It gave developers, implemented in ECMAScript 2017, the possibility to realize asynchronous operations in such a way that they looked and felt a bit more synchronous—hence, readable and easier to maintain.
Key Concepts:
Async function: A function declared via the async keyword; returns a Promise.
Await Expression: Suspends execution of the async function and waits for the resolution or rejection of the Promise. It can only be used inside an async function.
Using async/await
Declaring an Async Function
An async function is declared using the async keyword before the declaration of the function:
async function fetchData() {
// code
}
The Await Expression
The await
keyword can be used to pause the execution of an async function until a Promise
is resolved or rejected. It makes asynchronous code look synchronous:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
In this example, fetchData
is an async function that fetches data from an API. The await fetch('https://api.example.com/data')
pauses the function execution until the fetch
promise is resolved. Similarly, await response.json()
waits until the promise returned by response.json()
is resolved.
Error Handling with async/await
Error handling with async/await
can be done using try...catch
blocks:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
In this example, if any of the await
expressions throw an error, it is caught in the catch
block.
Advantages of async/await
Readability: Code written with
async/await
is easier to read and understand.Debugging: Easier to debug than traditional promise chains.
Error Handling: More straightforward error handling with
try...catch
.
Practical Example
Here’s a practical example of using async/await
to fetch multiple resources:
async function fetchMultipleData() {
try {
const [response1, response2] = await Promise.all([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2')
]);
const data1 = await response1.json();
const data2 = await response2.json();
console.log('Data 1:', data1);
console.log('Data 2:', data2);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchMultipleData();
In this example, Promise.all
is used to fetch multiple resources in parallel. The function waits for both fetch operations to complete before proceeding.
Conclusion
async/await
provides a powerful way to work with asynchronous code in JavaScript, making it more readable and easier to manage. By using async
functions and the await
keyword, developers can write code that looks synchronous but works asynchronously, improving both the structure and maintainability of their code.
Summary
async
keyword is used to declare an async function.await
keyword is used to wait for a promise to resolve.Error handling is done using
try...catch
blocks.Promise.all
can be used to run multiple promises in parallel.
By understanding and using async/await
, developers can write cleaner and more efficient asynchronous code in JavaScript.
Please login or create new account to add your comment.