Fetch API

As I was re-capping my work on AJAX and JavaScript XMLHttpRequest Objects (JSRS - JaveScript Remote Scripting) I came across the JavaScript Fetch API. This is not new, but again I seem to be late to the table. This is ironic as I was looking at this a long time ago before a lot of the current situation had been developed.

Both Syncronous and Asynchronous data exchanges between the client (web browser or app) and the server have become common. I have a few thoughts on how I could use these techniques, one of which is the loading of configuration settings on load.

First Example:

function loadDoc() {
let file = "site_config.txt" 

fetch (file) 
.then(x => x.text()) 
.then(y => document.getElementById("demo").innerHTML = y);
}

The button replaces the text below. As well as the button itself.

The content of this div, including the button will be replaced by the contents of the file on the server.

This will only work when run from the webserver.

The example above, when analysed, reveals other things that I was uaware. The JavaScript Promise with the then() method, async and await.

The .then() Method

The .then() method is part of the JavaScript Promise Object

myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

I have a page on the JavaScript Promise

Asynchronous Data Exchange - async and wait

AJAX - Asynchronous JavaScript And XML was the start of all this, well at least for me.

Links

External Sources

Fetch API - January 2021