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.
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.
function sayHello() {
return 'Hello World!';
}
sayHello(); // Hello World!
Copy
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