In JavaScript, async/await is an extension of promises which makes it easier to write promises. The keyword async before a function makes the function return a promise, always. And keyword await is used inside async functions, which makes the program wait until the Promise resolves.
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
We use the async keyword with a function to represent that the function is an asynchronous function.
async function test(param1, param2, ...paramN) {
//statements
}
Here,
test - name of the function
param - parameters that are passed to the function
async Function :
async function test() {
console.log("Async");
return Promise.resolve(1);
}
test();
Output:
Async
Since this function returns a promise, you can use the chaining method then() like this:
async function test() {
console.log("Async");
return Promise.resolve(1);
}
test().then(function (output) {
console.log(output);
});
Output:
Async
1
await Keyword :
The await keyword is used inside the async function to wait for the asynchronous operation.
let result = await promise;
The use of await pauses the async function until the promise returns a result value.
//a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Promise Resolved");
}, 4000);
});
//async function
async function asyncFunc() {
//wait until the promise resolves
let result = await promise;
console.log(result);
console.log("hello");
}
//calling the async function
asyncFunc();
Output:
Promise Resolved
hello
In the above program, a Promise object is created and it gets resolved after 4000 milliseconds.
Here, the asyncFunc() function is written using the async function.
Hence, hello is displayed only after promise value is available to the result variable.
The await keyword waits for the promise to be complete.
Error Handling :
While using the async function, you write the code in asynchronous manner.
And you can also use the catch() method to catch the error.
asyncFunc().catch(
//catch error and do something
)
The other way you can handle an error is by using try/catch block.
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Promise Resolved");
}, 4000);
});
async function asyncFunc() {
try {
//wait until the promise resolves
let result = await promise;
console.log(result);
} catch (error) {
console.log(error);
}
}
asyncFunc();
Benefits of Using Async Function :
The code is more readable than using a callback or a promise
Error handling is simple
Debugging is easier
Top comments (0)