SH BLOG
Feb 24, 2022

What is async await in Javascript?

First of all we have the async keyword, which you put in front of a function declaration to turn it into an . An async function is a function that knows how to expect the possibility of the await keyword being used to invoke asynchronous code.

Try typing the following lines into your browser's JS console:

function hello() { return "Hello" };hello();

Copy to Clipboard

The function returns "Hello" — nothing special, right?

But what if we turn this into an async function? Try the following:

async function hello() { return "Hello" };hello();

Copy to Clipboard

Ah. Invoking the function now returns a promise. This is one of the traits of async functions — their return values are guaranteed to be converted to promises.

You can also create an , like so:

let hello = async function() { return "Hello" };hello();

Copy to Clipboard

And you can use :

let hello = async () => "Hello";

Copy to Clipboard

These all do basically the same thing.

To actually consume the value returned when the promise fulfills, since it is returning a promise, we could use a .then() block:

hello().then((value) => console.log(value))

Copy to Clipboard

or even just shorthand such as

hello().then(console.log)

Copy to Clipboard

Like we saw in the last article.

So the async keyword is added to functions to tell them to return a promise rather than directly returning the value.

The advantage of an async function only becomes apparent when you combine it with the keyword. await only works inside async functions within regular JavaScript code, however it can be used on its own with

await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.

You can use await when calling any function that returns a Promise, including web API functions.

Here is a trivial example:

async function hello() {return await Promise.resolve("Hello");};hello().then(alert);

Copy to Clipboard

Of course, the above example is not very useful, although it does serve to illustrate the syntax. Let's move on and look at a real example.

Amir Yaqoob

Amir Yaqoob

I am Aamir Yaqoob. I am Full stack developer.

Leave a Reply

Related Posts

Categories