Sun Dial Menu
Menu Async Await
 

async, await and use of "producing code and consuming code"

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 (the asynchronous function) 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");
}

The JavaScript Promise

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

Top

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.

A disabled link.

tempusfugit.me.uk is a non-commercial website. No payment or benefit is gained by the placement of links to other websites.

External links disabled to on this page, please visit other pages

Site design by Tempusfugit Web Design -