async/await (Live Playground)
Async functions are a powerful feature in JavaScript that makes handling asynchronous operations, such as Promises, much simpler and cleaner. In this tutorial, we will explore the basics of async functions and how they can improve your code.
Defining an Async Function
An async function is defined using the async
keyword before the function declaration. This implicitly makes the function return a Promise.
Example:
async function fetchData() {
return 'Data fetched';
}
fetchData().then(data => console.log(data));
Using await
The await
keyword can only be used inside an async
function. It allows you to wait for a Promise to resolve before continuing the execution of the code.
Example:
async function fetchData() {
return 'Data fetched';
}
async function fetchAndProcessData() {
const data = await fetchData();
console.log('Data:', data);
// Continue processing the data
}
fetchAndProcessData();
Awaiting Multiple Promises
You can use await
with multiple Promises. However, this might lead to slower execution times as each Promise resolves sequentially.
Example:
async function fetchData1() {
return 'Data 1 fetched';
}
async function fetchData2() {
return 'Data 2 fetched';
}
async function processAllData() {
const data1 = await fetchData1();
const data2 = await fetchData2();
console.log('Data1:', data1, 'Data2:', data2);
}
processAllData();
Awaiting Multiple Promises Concurrently
To avoid waiting for multiple Promises sequentially, you can use Promise.all()
to execute them concurrently.
Example:
async function fetchData1() {
return 'Data 1 fetched';
}
async function fetchData2() {
return 'Data 2 fetched';
}
async function processAllDataConcurrently() {
const [data1, data2] = await Promise.all([fetchData1(), fetchData2()]);
console.log('Data1:', data1, 'Data2:', data2);
}
processAllDataConcurrently();
Async/Await Error Handling
When working with asynchronous code in JavaScript, it's essential to handle errors effectively. With async/await, you can use try/catch blocks to catch and handle errors gracefully.
Basic Error Handling with Try/Catch
When using async/await, you can catch errors by wrapping the await
expressions in a try/catch block.
Example:
async function fetchData() {
// Simulating an error
throw new Error('Data fetching failed');
}
async function processData() {
try {
const data = await fetchData();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error.message);
}
}
processData();
Handling Multiple Errors
You can handle multiple errors from different await expressions using nested try/catch blocks or by having multiple catch blocks.
Example:
async function fetchData1() {
throw new Error('Data 1 fetching failed');
}
async function fetchData2() {
throw new Error('Data 2 fetching failed');
}
async function processAllData() {
try {
const data1 = await fetchData1();
console.log('Data1:', data1);
} catch (error) {
console.error('Error1:', error.message);
}
try {
const data2 = await fetchData2();
console.log('Data2:', data2);
} catch (error) {
console.error('Error2:', error.message);
}
}
processAllData();
Using Finally Block
You can use a finally
block after the try/catch block to execute code regardless of whether an error occurs.
Example:
async function processData() {
try {
const data = await fetchData();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error.message);
} finally {
console.log('Process completed');
}
}
processData();
Conclusion
Async functions in JavaScript provide a more straightforward and manageable way to handle asynchronous operations. By using async
, await
, and proper error handling, you can write clean, readable, and maintainable code.