Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Await Syntax

The await keyword can only be used inside an async function. It pauses the function’s execution, waiting for a resolved Promise before continuing.

let value = await promise;

Example

Let’s take it step by step and learn how to use it.

Basic Syntax

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

myDisplay();

The two arguments, resolve and reject, are predefined by JavaScript. We don’t create them ourselves; instead, we call one of them when the executor function completes. In many cases, we may not need the reject function.

Example without reject

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

myDisplay();

Waiting for a Timeout

async function myDisplay() {
  let myPromise = new Promise(function(resolve) {
    setTimeout(function() {resolve(“I love You !!”);}, 3000);
  });
  document.getElementById(“demo”).innerHTML = await myPromise;
}

myDisplay();

Waiting for a File

async function getFile() {
  let myPromise = new Promise(function(resolve) {
    let req = new XMLHttpRequest();
    req.open(‘GET’“mycar.html”);
    req.onload = function() {
      if (req.status == 200) {
        resolve(req.response);
      } else {
        resolve(“File not Found”);
      }
    };
    req.send();
  });
  document.getElementById(“demo”).innerHTML = await myPromise;
}

getFile();

Browser Support

ECMAScript 2017 introduced the async and await keywords in JavaScript.

 

The following table shows the first browser version to fully support both features:

js 23