JavaScript

What are Async/Await Functions in JavaScript

As we all know, the single threaded nature of JavaScript makes it synchronous; So asynchronous functions are necessary to perform any asynchronous task. The Asynchronous functions allow us to perform one action without waiting for the previous action to complete. That means that there is an event loop that allows you to queue up a task (when it’s requesting for some resources) and move onto the next.

JavaScript offers many features that can make the code asynchronous; async await functions are one of them. The async/await functions are just syntactic sugar on top of already present features in JavaScript. They provide a simple way to handle asynchronous code. The async/await functions can be interchanged with promises in JavaScript code and the code will work perfectly fine

Human brains are not designed to handle asynchrony efficiently. The async/await functions allow us to write code that looks synchronized but executes it asynchronously.

This article will assist you in learning about async and await functions in JavaScript.

Why to use async/await functions?

Following are the reasons why async/await functions should be used in JavaScript code:

  • We can write clean and concise code with a few errors using async/await. This will increase the readability of nested and complex code.
  • Helps in Debugging. Errors can be handled in one place by using try/catch.
  • The async/await functions have a proper error stack, unlike the ambiguous stack received by Promise, which makes it difficult to find where the error occurred.

How to use async in JavaScript

Async is a keyword that can be used for the declaration of synchronous functions. Through the async function, you can make sure that you don’t break the thread of execution, which can be written like synchronizing promise-based code.

Features of async Function

  • Works asynchronously through an event loop
  • Always returns a value
  • It checks that a promise returns, and if it doesn’t, JavaScript automatically wraps it with the promise it resolves to that value

Syntax of async Function

The syntax of the async function is as follows:

async function name([param1[, param2[, ...param3]]]) {
 statements
}

Here, the name represents the function name, params represent the name of parameters to be passed in the function, and statements contain the body of the function and one or more await expressions used within the async function.

A Simple Example of async Function

const getData = async() => {
 var data = "Hello World";
 return data;
}

getData().then(data => console.log(data));

Let’s take a look at another example:

async function foo() {
await 1;
}

The above function is equivalent to the following function:

function foo() {
 return Promise.resolve(1).then(() => undefined)
}

Above example represents that the code after each await expression is likely to be in the callback i.e .then. Through the functions, the promise chain is automatically constructed step by step at each reentry stage. The return value forms the last step in the chain.

How to use await in JavaScript

The purpose of the await expression is to wait for JavaScript before the return result of the promise. It is important to note that this will only queue an asynchronous function block, not the execution of the entire program.

Features of Await Function

  • Can only be used within asynchronous blocks.
  • Makes the code wait for the Promise to return a result.
  • Only asynchronous blocks will be kept waiting.

Syntax of Await Function

The syntax of await expression is as follows:

[rv] = await [expression]

Here, await represents any value to wait for or promise, rv returns the value if there is no promise, or else returns the expected value of the promise.

A Simple Example of await Expression

const getData = async => {
 var y = await "Hello World";
 console.log(y);
}

console.log(1);
getData();
console.log(2);

JavaScript executes code sequentially.

In the example above we can see that the console.log(1) was printed first as expected. After this the getData() function was called where we initiated a variable with the name of y and we used the await keyword in it.

The await keyword will cause the JS runtime to stop or pause the code in that line i-e where we have written “Hello world”. It won’t allow the execution of further code until the async function call returns the result.  It will send this task to the task queue and the next lines of code will start to run.

In the next line after calling the function getData() we are console logging the 2 to the console window. Hence we saw 2 before “Hello world”.

Now after this when the async call function returns the result only then will the code resume to run again and hence we see “Hello World” at the end of the console window.

Conclusion

The async and await functions are a great way of handling asynchronous code in JavaScript as they provide clear and concise syntax. In this post we explored the concept of async/await functions in JavaScript. In the first half of the article we explored what async/await functions are and why we should use them. Then we explored their features and syntax along with examples.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.