In JavaScript to make Asynchronous programming easier to implement and read, Special Async and Await keywords were introduced.
Lets see why these are used
These functions can be used in multiple use cases where a function execution depends on the output of the previous function call and it needs to wait for it An
easy example for this is an API call, where the data from the API call need to be fetched first before doing other operations on it.
Async
An Async function can be declared by adding the Async keyword in front of a function. This function returns a promise
It can be declared like this
const test = async () => {
console.log("Async function")
}
Await
An await function can be declared in the same way as an Async function by adding the Await keyword in front of the function declaration.
const test = await () => {
console.log("Async function")
}
Await keyword can only be declared inside an Async function.
Await keyword makes the code execution stop from the line it is declared till the promise completes. While it does stop the execution of the code from the line it is declared. It does not stop the code execution outside the Async block.
Now that we know how to write these functions individually lets see what we can achieve with these functions.
const testFunc = async () => {
const a = await "Hello World!"
console.log(a;
}
console.log("Before testFunc() call")
testFunc()
console.log("After testFunc() call")
Output
Before testFunc() call
After testFunc() call
Hello World
Top comments (0)