Async/Await Function in JavaScript

We all know that Javascript is a Synchronous which means that it has an event loop that allows you to queue up an action that won’t take place until the loop is available sometime after the code that queued the action has finished executing. But there’s a lot of functionalities in our program which makes our code Asynchronous. One of them is the Async/Await functionality.

Async/Await is the extension of promises which we get as a support in the language. You can refer Promises in Javascript to know more about it.

Async:
It simply allows us to write promises based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event-loop. Async functions will always return a value. It makes sure that a promise is returned and if it is not returned then javascript automatically wraps it in a promise which is resolved with its value.



Examples:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Hello World



Await:
Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It only makes the async block wait.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

1
2
Hello World

Notice that the console prints 2 before the “Hello World”. This is due to the usage of the await keyword.

Supported Browsers: The browsers supported by Async/Await Function are listed below:

  • Google Chrome
  • Firefox
  • Apple Safari
  • Opera


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.