JavaScript Async

Async Syntax

The keyword async before a function makes the function return a promise:


Example
async function myFunction() {
  return "Hello";
}

Is the same as:

async function myFunction() {
  return Promise.resolve("Hello");
}

Here is how to use the Promise:

myFunction().then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

Await Syntax

The keyword await before a function makes the function wait for a promise:

let value = await promise;

The await keyword can only be used inside an async function.

Example
async function myDisplay() {
  let myPromise = new Promise(function(resolve, reject) {
    resolve("I love You !!");
  });
  document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();