Harshil Chovatiya - Day 32: Async/Await Syntax.
Building on our understanding of Promises, today, we'll explore the async/await syntax, which is a powerful and more intuitive way to work with asynchronous code in JavaScript. Async/await simplifies asynchronous operations and enhances code readability. Let's delve into the concepts and usage of async/await.
1. Introduction to Async/Await:
Async/await is a modern JavaScript feature that allows you to write asynchronous code in a more synchronous and structured manner. It involves two main keywords:
async
: It is used to define a function as asynchronous. Async functions always return a Promise, either resolved with the return value or rejected with an exception.await
: It is used inside an async function to pause the execution until a Promise is resolved. It is followed by a Promise, and it "waits" for the Promise to resolve, returning the resolved value.
Here's a basic example:
async function fetchData() {
return new Promise(function (resolve) {
setTimeout(function () {
const data = 'Data from the server';
resolve(data);
}, 2000);
});
}
async function getData() {
try {
const data = await fetchData();
console.log(`Data received: ${data}`);
} catch (error) {
console.error(`Error: ${error.message}`);
}
}
getData();
In this example, we have an async
function getData
that uses await
to
pause execution until the Promise returned by fetchData
resolves. This makes the code read more
like synchronous code.
2. Error Handling with Async/Await:
Async/await makes error handling straightforward. You can use a try/catch
block to catch and
handle errors. If the Promise rejects, it throws an exception, which can be caught and handled in the
catch
block. Here's an example:
async function performAsyncTask() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
const error = true; // Simulate an error
if (error) {
reject(new Error('An error occurred.'));
} else {
resolve('Task completed successfully.');
}
}, 1000);
});
}
async function runTask() {
try {
const result = await performAsyncTask();
console.log(`Result: ${result}`);
} catch (error) {
console.error(`Error: ${error.message}`);
}
}
runTask();
In this example, if an error occurs in performAsyncTask
, it is caught in the catch
block of the runTask
function.
3. Sequential and Parallel Execution:
Async/await allows you to perform tasks sequentially or in parallel easily. You can use multiple
await
statements for sequential execution or wrap Promises in Promise.all()
for
parallel execution. Here's a sequential execution example:
async function doSequentialTasks() {
const result1 = await performTask1();
const result2 = await performTask2();
console.log(result1, result2);
}
doSequentialTasks();
For parallel execution, you can use Promise.all()
:
async function doParallelTasks() {
const [result1, result2] = await Promise.all([performTask1(), performTask2()]);
console.log(result1, result2);
}
doParallelTasks();
Async/await simplifies the structure and readability of your asynchronous code, making it easier to understand and maintain. In the following days, we'll delve deeper into more advanced concepts and use cases for async/await.
Conclusion:
Async/await is a powerful feature in JavaScript that simplifies asynchronous code and improves readability. It allows you to write asynchronous code in a more synchronous style, making it easier to work with Promises. With proper error handling and the ability to perform tasks sequentially or in parallel, async/await is a valuable tool for modern web development.
Comments
Post a Comment