async and await

This page shows an example of how the Fetch() method csn be used to read text from a file on the webserver. The file in this case is called fetch_info.txt The file can contain anything you like, in my case you will see the contents when you click the button (or here).

The syntax of async is:

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

async function myFunction() {
  return "Hello";
}
Is the same as:

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

2nd Example from W3C Fetch API page:

I changed the example to "fire" from a button. I commented out the function getText("fetch_info.txt") from the script.

<button type="button" onclick="getText('fetch_info.txt')">Change Content</button>

<script>
// getText("fetch_info.txt");

async function getText(file) {
  let x = await fetch(file);
  let y = await x.text();
  document.getElementById("demo").innerHTML = y;
}
</script>

THIS NEEDS TO RUN FROM SERVER

await

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

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

An example that also includes a time-out before the "consuming code" executes.

script>
async function myDisplay() {
  let myPromise = new Promise(function(myResolve, myReject) {
    setTimeout(function() { myResolve("Refresh page to reset"); }, 3000);
  });
  document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();
/script>

The text below will be replaced after a time-out

Wait 3 seconds (3000 milliseconds) for this page to change.

Links

External Sources

async and await - January 2021