Javascript Async Arrow Function
When I was using the Promise object with .then() and .catch() methods to handle asynchronous operations. I had a situation to chaining multiple .then() calls in promise, the code was hard to follow, especially when error handling is involved. I researched whether there is another way for this, then I found out that we can do the same functionality by using an async function with await keyword. We can also write an understandable asynchronous operation without nesting in an async function. We can use the async arrow function to make the async function more convenient. So, this post tells about how to use the async arrow function in Javascript.
What is an async function?
If we use async functions with the “await” keyword, we can write Asynchronous code in a more linear and sequential manner. If you put the “async” keyword before the traditional function, your normal function will become an async function. An async function always returns a promise.
In the code below, we’ve returned some string in the sync function, that returns data in the promise.
async function fetchData() {
return "data"
}
console.log(fetchData())
We should await the keyword only inside the async function. The “await” keyword allows you to wait for the execution of an async function until the awaited Promise resolves, which makes it easier to control the flow of your code.
In the example below, we create a promise called
checkReach
and access it in an async function. Here we have used await keyword, so checkReach
waits until the promise resolves.// creating promise
let checkReach = new Promise((resolve, reject) =>{
const reached = true
if(reached)
setTimeout(resolve, 2000, "Vidya Reached")
else
reject("Not Reached")
})
//Create async function
async function getStatus(){
console.log("wait for result...")
res = await checkReach
console.log(res)
}
getStatus() // calling the function
If the promise returns an error message to handle that we can use normal
try-catch blocks
.// creating promise with error
let checkReach = new Promise((resolve, reject) =>{
const reached = false
if(reached)
setTimeout(resolve, 2000, "Vidya Reached")
else
reject("Not Reached")
})
//Create async function with try and catch block
async function getStatus(){
try {
console.log("wait for result...")
res = await checkReach
console.log(res)
}
catch(error){
console.log(error)
}
}
getStatus() // calling the async function
How to create the async arrow function?
Whether you create an async regular function or async arrow function syntax, both of them perform the same functionality, only the syntax is different. Most developers use the arrow function because its syntax is simple and I prefer the arrow function because the “function” keyword is often used when creating a normal asynchronous function. We can also use the “await” keyword and try-catch block inside the function. The syntax of the async arrow function is:
const myAsyncFunction = async () => {
// Asynchronous code using await
};
We must put the keyword “async” (=>) before the arrow to indicate that the function is asynchronous.
The async arrow function with error handling looks like this:
//Creating promise, it returns one promise
let coinToss = new Promise((resolve, reject) =>{
//0-head(success) 1-tail(fail)
const rand = Math.floor(Math.random()*2)
if(rand==0)
setTimeout(resolve, 2000, "Won! Head")
else
setTimeout(reject, 2000, "Loss! Tail")
})
//Creating Arrow Async Function
const getResult = async () =>{
//if the condition of the promise is true (try block) will execute
try{
console.log("wait for result...")
result = await coinToss
console.log(result)}
//if the condition of the promise is false (catch block) will execute
catch(error){
console.log(error)
}
}
getResult()
In this code, we are using the “await” keyword for the promise “
coinToss
“, it waits until the promise returns. So, we log that “result”, if the condition of the promise is true will execute else the error block will be execute.You can pass the parameter to the async arrow function in parentheses after the arrow (=>) symbol. You can also pass as multiple parameters as needed to the async arrow function. The syntax for async arrow function with parameter is:
const myAsyncArrowFunction = async (para1, para2, ...) => {
// Asynchronous code using await
};
In the below example, we have passed two parameter in the ”
fetchData
” async arrow function, which is (url and options). When we call the function, the value is assigned to these parameters and it is passed into the function.//Creating passing argument
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
};
// Using async arrow function with parameter
const fetchData = async (url, options) => {
try {
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
//calling the function with passing argument
fetchData('https://api.example.com/data', requestOptions);
Conclusion
Whether you create the async function in the arrow method or the regular create method, both of them are going to do the same work. So, you can use whichever syntax is easier for you.