An Overview of JavaScript Async/Await
Through this blog, you will learn about javascript async/await functionality but before going in depth about it let’s see what javascript is.
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();
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);});
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.
Best-suited JavaScript courses for you
Learn JavaScript with these high-rated online courses
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”);
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();
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.
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
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