38.3. Getting Data from a Public API - Fetch

With the help of MDN

38.3.1. Reading Files with Fetch

Example 38.1. The Application HTML5 - fetchpromise/promise-all-async-await.html - Debugging Mode
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>promise.all() example with async/await</title>
        <style>
            main {
                padding: 1em;
            }
            img {
                border: 1px solid black;
                margin: 1em;
            }
        </style>
        <script src='promiseall.js'></script>
    </head>
    <body>
        <header><h1>Niels' Header</h1></header>
        <main></main>
        <footer><h6>Niels' footer</h6></footer>
    </body>
</html>

            

Click here!


Example 38.2. The Application JavaScript, fetchpromise/promiseall.js - Debugging Mode
'use strict';
/*
 * This code is lifted directly from
 * https://github.com/mdn/learning-area.git
 */
// Define function to fetch a file and return it in a usable form
async function fetchAndDecode(url, type) {
    // Returning the top level promise, so the result of the entire chain is returned out of the function
    let response = await fetch(url);

    let content;

    // Depending on what type of file is being fetched, use the relevant function to decode its contents
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    } else {
        if(type === 'blob') {
            content = await response.blob();
        } else if(type === 'text') {
            content = await response.text();
        }
        return content;
    }
}

async function displayContent() {
    // Call the fetchAndDecode() method to fetch the images and the text, and store their promises in variables
    let coffee = fetchAndDecode('coffee.jpg', 'blob');
    let tea = fetchAndDecode('tea.jpg', 'blob');
    let description = fetchAndDecode('description.txt', 'text');

    // Use Promise.all() to run code only when all three function calls have resolved
    let values = await Promise.all([coffee, tea, description]);

    console.log(values);
    // Store each value returned from the promises in separate variables; create object URLs from the blobs
    let objectURL1 = URL.createObjectURL(values[0]);
    let objectURL2 = URL.createObjectURL(values[1]);
    let descText = values[2];

    // Display the images in <img> elements
    let image1 = document.createElement('img');
    let image2 = document.createElement('img');
    image1.src = objectURL1;
    image2.src = objectURL2;
    let main = document.getElementsByTagName('main');
    main = main[0];
    main.appendChild(image1);
    main.appendChild(image2);

    // Display the text in a paragraph
    let para = document.createElement('p');
    para.textContent = descText;
    main.appendChild(para);
};

displayContent()
.catch( function (e) {
    console.log(e)
});