An Overview of JavaScript Async/Await

An Overview of JavaScript Async/Await

4 mins read403 Views Comment
Updated on Nov 23, 2022 13:13 IST

Through this blog, you will learn about javascript async/await functionality but before going in depth about it let’s see what javascript is.

2022_11_Javascript-Async-Await.jpg

JavaScript is a scripting and programming language that enables the implementation of complex features on web pages. Whenever a web page displays anything other than static information for you to look at, such as timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc., you can bet that JavaScript is being used. JavaScript is frequently used in conjunction with the Document Object Model API to edit HTML and CSS to refresh user interfaces dynamically. The code in your web documents loads and processes in the order it appears on the page, so keep this in mind. If JavaScript loads and is activated before the HTML and CSS it is meant to change, errors could happen.

Explore: Compare Best HTML Courses to learn in 2023

Since JavaScript is synchronous, you can queue up an action to be performed after the queued code has run until the event loop becomes available. However, several features in our application, including the JavaScript Async/Await capabilities, make our code asynchronous. The extension of promises that the language provides as support is known as async/await. So, let’s know about JavaScript Async/Await functions.

Check out: Free JavaScript Courses Online

Table of Content

Async Keyword

It only enables us to build code that uses promises as though it were synchronous and verifies that we aren’t interfering with the execution thread. It uses the event loop to run asynchronously.

When a function is prefixed with the word “async,” it simply signifies that it will always return a promise. A resolved promise automatically wraps other values.

Syntax of async:

async function func_name(params)
{
block of code
}

Return value:

A Promise that will be fulfilled by the async function’s value or refused with an exception that is either thrown by the async function or goes uncaught inside of it.

Example:

 
async function fun()
{
console.log(“Overview of async function);
return Promise.resolve(1);
}
fun();
Copy code

Output:

Overview of async function

In the above example async is used before function fun so it means that the function is asynchronous. As the above function will return a Promise chaining method then() can be used with it. For example

 
async function fun()
{
console.log(“Overview of async function);
return Promise.resolve(1);
}
fun().then(function(res)
{
console.log(res);
});
Copy code

Output:

Overview of async function
1

In this example, function fun() is resolved first and the then() method is executed.

You can think of an async function’s body as being divided into two or more sections by await expressions. But the async function will always end asynchronously if the function body contains an await statement.

Await Keyword

One should use the await function to keep the promise in await condition. It could only be used inside an async block. The code is forced to wait till the promise responds. Only the async block is delayed by it.

One should pass promise as the expression when using await to unwrap promises. When an async function uses await, the execution suspends until the promise is fulfilled (fulfilled or rejected). The value of the await expression changes to that of the fulfilled promise when execution is resumed.

If a promise refuses, await expression throws a rejection value. The error’s stack trace will show the function that the await statement is in. Otherwise, the caller function won’t show up in the stack trace if the promise in the rejection state is not awaited or returns quickly.

Syntax:

let a=await promise;

Example:

 
const str = async() =>
{
var a=await “Hello”;
console.log(a);
}
console.log(A);
str();
console.log(B);
Copy code

Output:

A
B
Hello

Due to await keyword, Hello is printed after B.

To understand the concept in deep let’s see another example:

 
let p= new Promise(function (resolve, reject)
{
setTimeout(function () {
resolve(“Resolve promise”)},2000);
});
async function fun()
{
let res=await p;
console.log(res);
console.log(“hello world”);
}
fun();
Copy code

Note:

  • Resolve and Reject are the two predefined arguments in JavaScript.
  • When the executor function is prepared, we will call one of them rather than create them.
  • We won’t require a reject function very often.
JavaScript Uses in Various Sectors
JavaScript Uses in Various Sectors
Many websites utilize the lightweight, object-oriented programming language JavaScript to write their web pages. It is a complete programming language that is interpreted. When used with HTML, JavaScript allows dynamic...read more
Introduction to JavaScript Data Types With Examples
Introduction to JavaScript Data Types With Examples
JavaScript supports several data types including numbers, strings, booleans, arrays, objects, null, and undefined. Numbers represent numeric values, strings represent text, booleans represent true or false values, arrays store multiple...read more
15+ JavaScript Array Methods with Examples
15+ JavaScript Array Methods with Examples
JavaScript array methods offer powerful tools for manipulating arrays. Key methods include 'push()' and 'pop()' for adding/removing elements at the end, 'shift()' and 'unshift()' for operations at the beginning, 'map()'...read more

Output:

Resolve Promise
hello world

In the above example an object has been created and it will resolve in 2000 ms. And fun() is declared as async. Since await is used so hello world be printed only when the promised value is available to the res variable.

Note: If await was not used then hello world would be printed first.

The async function enables the execution of the asynchronous method in a manner that appears synchronous. Despite being asynchronous, the operation appears to be carried out synchronously.

Summary

If the async keyword is used before the function then it has two main effects:

  • That function will always return a promise.
  • Await must be used with it.

Check out: Top 85+ JavaScript Interview Questions and Answers for 2022

Conclusion

This blog gives an overview of what is JavaScript. After that, you will have deep insights into the JavaScript async/await keywords. Hope you will be able to use these two keywords more accurately in your program.

Check out: Top 62 HTML Interview Questions and Answers for 2022

Contributed by: Urvashi Saxena

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio