RandomAjax (using Fetch API)
A JS program that asynchronously get (by using the Fetch API) a sequence of numbers generated by random.org.
by Sabin Buraga
HTML
<div id="numbers">[Wait, please...]</div>
CSS
#numbers {
font-family: monospace;
font-size: 1em;
width: 12em;
}
JavaScript
// A JS program that asynchronously get (by using the Fetch API) a sequence of numbers generated by random.org. See also "Introduction to fetch()": https://developers.google.com/web/updates/2015/03/introduction-to-fetch
const URL = 'https://www.random.org/sequences/?min=1&max=33&col=1&format=plain&rnd=new';
function status(response) {
// using promises -- https://github.com/wbinnssmith/awesome-promises --
// to perform the desired processing depending on the returned HTTP status code
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response) // request can be fulfilled
} else {
return Promise.reject(new Error(response.statusText)) // request is rejected
}
}
const numbers = document.getElementById('numbers');
fetch(URL)
.then(status) // checking if data was successfully received
.then((response) => response.text()) // transforming received data into a string
.then(function(response) { // processing the number sequence
// substituting white spaces with comma and
// putting the content into the HTML element identified by 'numbers'
numbers.textContent = response.trim().replace(/\W+/g, ', ');
})
.catch(function(error) { // an error occurred :(
numbers.textContent = 'An error occurred: ' + error;
});