1

I have some files in JSON format and their names are something like this:

chapter1.json, chapter2.json, chapter3.json , ...

I want to fetch the content of the files with Promises in javascript and show them in sequence in a HTML page. But I don't want to repeat then() method. Instead I want to use for loop. I don't want to use node.js.

Can anyone please help me how to do that? Thanks very much.

0

1 Answer 1

2

I found my answer.

function get(url) {
// Return a new promise.
return new Promise(function (resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function () {
        // This is called even on 404 etc
        // so check the status
        if (req.status == 200) {
            // Resolve the promise with the response text
            resolve(req.response);
        }
        else {
            // Otherwise reject with the status text
            // which will hopefully be a meaningful error
            reject(Error(req.statusText));
        }
    };

    // Handle network errors
    req.onerror = function () {
        reject(Error("Network Error"));
    };

    // Make the request
    req.send();
});
}
function getJSON(url) {
return get(url).then(JSON.parse);
}
$(function () {
getJSON('story.json').then(function(story) {
    $("#message").append(story.heading);

    // Take an array of promises and wait on them all
    return Promise.all(
        // Map our array of chapter urls to
        // an array of chapter json promises
        story.chapterUrls.map(getJSON)
    );
}).then(function(chapters) {
    // Now we have the chapters jsons in order! Loop through…
    chapters.forEach(function(chapter) {
        // …and add to the page
        $("#message").append(chapter.html);
    });
    $("#message").append("All done");
}).catch(function(err) {
    // catch any error that happened so far
    $("#message").append("Argh, broken: " + err.message);
}).then(function() {
    document.querySelector('.spinner').style.display = 'none';
});
});

The story.json is:

{
  "heading": "<h1>A story about something</h1>",
  "chapterUrls": [
  "chapter-1.json",
  "chapter-2.json",
  "chapter-3.json",
  "chapter-4.json",
  "chapter-5.json"
   ]
}

This code first fetch all of the chapters in parallel and then displays them in order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.