0

Can anyone please help me with this code to make console.log(var1) work when var1 is being set within a function that takes a little time. Here is the basic problem to replicate:

<script>
  var var1;

  async function loadSuccess() {
    await setTimeout(() => {
      console.log("waiting 5000 ms");
    }, 5000);
    var1 = "success";
  }
  loadSuccess();
</script>

<script>
  console.log(var1);
</script>

Since loadSuccess() takes an extra 5000ms to complete, console.log(var1) prints undefined because it runs before loadSuccess() is finished.

Can anyone help fix the code in this example to make it console.log(var1) return "success" in the 2nd script?

DecPK
  • 24,537
  • 6
  • 26
  • 42
haliofin
  • 11
  • 4

1 Answers1

0

This might help:

var var1;

function loadSuccess() {
    return new Promise((resolve, reject) => {
        console.log("waiting 5000 ms");
        setTimeout(() => {
            var1 = "success";
            resolve(var1);
        }, 5000);
    });
}
loadSuccess().then((var1) => document.write(var1));

Also, setTimeout is not an asynchronous function so you do not need async/await with it.

Lakshaya U.
  • 1,089
  • 1
  • 5
  • 21