How To Use Async/Await in JavaScript

SHARE     

Async/Await

The async and await is keywords to perform the promise-based asynchronous operation. In this article, we are going to learn how to use async/await in JavaScript.

How to use Async?

It is mandatory to define the async keyword before any function that turns your normal function to async function. Let’s start to learn it through a very basic example.

Normal Function Example

function sayHello() {
    return 'Hello World!';
}

sayHello(); // Hello World!

Copy

Async Function Example

async function sayHello() {
    return 'Hello World!';
}

sayHello(); // [object Promise] { ... }

Copy

We could explicitly return a promise with Promise.resolve() like:

async function sayHello() {
    return Promise.resolve('Hello World!');
}
async function sayHello() {
    return 'Hello World!';
}

let greeting = sayHello();
greeting.then((value) => console.log(value)); // Hello World!

Copy

or you can try this:

async function sayHello() {
    return 'Hello World!';
}

sayHello().then((value) => console.log(value) ); // Hello World!

#javascript #async #await

How To Use Async/Await in JavaScript
4.45 GEEK