Daros911
Daros911

Reputation: 435

Async function and await keyword

Having such a simple js app:

index.html:

<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app1"></div>
    <div id="app2"></div>
    <div id="app3"></div>
    <div id="app4"></div>

    <script src="src/js1.js"></script>
    <script src="src/js2.js"></script>
  </body>
</html>

js1.js:

async function myDisplay() {
  let myPromise = new Promise(function (myResolve, myReject) {
    setTimeout(function () {
      myResolve("I love You 1 !!");
    }, 4000);
  });
  document.getElementById("app3").innerHTML = await myPromise;
  document.getElementById("app4").innerHTML = "myDisplay 1";
}

myDisplay();

js2.js:

function myDisplay2() {
  let myPromise = new Promise(function (myResolve, myReject) {
    setTimeout(function () {
      myResolve("I love You 2 !!");
    }, 2000);
  }).then(function (resp) {
    document.getElementById("app1").innerHTML = resp;
  });
  document.getElementById("app2").innerHTML = "myDisplay2";
}

myDisplay2();

Why does the function myDisplay with the await keyword in the js1.js script HAVE to be declared as async while the function myDisplay2 in the js2.js script doesn't have?

Upvotes: 0

Views: 401

Answers (1)

Coolhand
Coolhand

Reputation: 106

Inside js1.js the function execute a promise that is asynchronous and you want it to wait for the Promise's result :

document.getElementById("app3").innerHTML = await myPromise;

At this point, the function will stop and wait for the "myPromise" to complete (resolve or reject). More on : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Operators/await

The function inside js2.js do not executes code that block it's execution, myDisplay2 can be executed in a synchrone way, the result of the promise will be executed later (if the promise resolve) in the :

.then(function (resp) { document.getElementById("app1").innerHTML = resp; });

To make it short, as soon as you are using "await" the function is "async".

Upvotes: 1

Related Questions