In JavaScript, the async/await syntax offers a more streamlined and comprehensible approach to handling promises, allowing asynchronous code to resemble synchronous code more closely.
The keyword async is utilized to define a function as asynchronous, while await temporarily halts execution until a promise is fulfilled, thereby streamlining the management of asynchronous tasks.
Syntax
async function myFunction() {
const result = await somePromise(); // Pauses until somePromise resolves
console.log(result);
}
What is an Async Function in JavaScript?
In JavaScript, the async function facilitates the creation of promise-oriented code that appears more synchronous in nature, thereby allowing us to guarantee that the execution thread remains unblocked. This function will invariably return a promise, even if it does not explicitly return one.
Syntax
The syntax of an async function is as follows:
async function myFunction() {
//Code to be executed
}
Example
const demo = async() => {
let greet = "Hello, Welcome to our tutorial";
return greet;
}
demo().then(greet => console.log(greet));
Output:
Hello, Welcome to our tutorial
What is an Await Keyword in JavaScript?
In JavaScript, the keyword await is employed to extract values from promises by providing a Promise as an expression. By utilizing await, you can temporarily halt the execution of the encompassing async function until the promise is fulfilled.
Upon the resumption of execution, the result of the await expression is the value of the promise that has been successfully fulfilled.
Syntax
The structure of the await keyword in JavaScript is outlined below:
let value = await promise;
Example
const demo = async() => {
let a = await "Hello, Welcome to our tutorial";
console.log(a);
}
console.log(1);
demo();
console.log(2);
Output:
1
2
Hello, Welcome to our tutorial
Example 2
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
}
f();
How Does Async/Await Work?
In JavaScript, an async function may include none or multiple await expressions. These await expressions transform the behavior of functions that return promises, allowing them to operate as if they are synchronous by halting execution until the promise has either been resolved or rejected.
The value that the promise resolves to is regarded as the return value of the await expression.
Async Keyword
In JavaScript, when you define a function using the async keyword, it inherently transforms into an asynchronous function that yields a promise.
Await keyword
The keyword await is utilized to extract values from promises by supplying a Promise as the expression. By employing await, you can temporarily halt the execution of the encompassing async function until the promise has been fulfilled.
Promise resolution
In JavaScript, once a promise is fulfilled, the execution flow of the async function continues, and the value obtained from the resolved promise becomes accessible.
Execution resumption
Once the promise is resolved, the asynchronous function resumes its execution from the point at which it was interrupted, and the await expression is evaluated to yield the resolved value of the promise.
Non-blocking Nature
In JavaScript, as one segment of the program is pending the resolution of a promise, another segment can continue to run concurrently in the background.
Error Handling in Async/Await
JavaScript includes predefined parameters for managing promises: resolve and reject.
resolve: This is utilized when an asynchronous operation has been successfully finalized.
The reject method is utilized when an asynchronous operation encounters a failure, and it delivers the rationale behind the failure.
Example
async function fetchData() {
try {
// Simulate a fetch with a promise that rejects
let response = await fakeApiCall();
console.log("Data received:", response);
} catch (error) {
console.error("Error occurred:", error.message);
}
}
// Simulated async API call that fails
function fakeApiCall() {
return new Promise((_, reject) => {
setTimeout(() => {
reject(new Error("Failed to fetch data"));
}, 1000);
});
}
fetchData();
Output:
Runtime Error:
Error occurred: Failed to fetch data
Advantages of Async/Await
There are some advantages of async/await in JavaScript. Such as:
- Improved Readability: JavaScript async/await makes asynchronous code look and feel more like synchronous code, which makes it easier to understand and maintain.
- Simplified Error Handling: The try…catch block provides a cleaner and more straightforward way to handle errors with asynchronous functions compared to promise chaining.
- Easier Debugging: With async/await, you can use breakpoints in the same way as with synchronous code, which makes it easier to step through the execution flow.
- Elimination of callback hell: By using JavaScript async/await, we can prevent nested callbacks and complex promise chains, which makes the code more linear and readable.
- Enhanced Code Structure: By using async/await, you can make the structure of asynchronous functions, which makes it easier to follow the logic and flow of the code.
Conclusion
To summarize, the async/await feature in JavaScript serves as a powerful resource that enables developers to construct asynchronous code that resembles synchronous code. This functionality simplifies the process of managing promises and enhances the ease of error handling.