Allison Stafford Allison Stafford - 5 months ago 14
Ajax Question

How can I run $.ajax through a list?

When I run $.ajax multiple times, it doesn't seem to wait for the ajax call to finish before continuing to run my code.
As I am using jsonp, setting 'async: false' doesn't work (or so I've read). I have to jsonp to access the Media Wiki api, so changing that isn't an option. I am a beginner at Javascript, is this something I could use a 'promise' for?

var articleList = ['Abaft', 'Aspect-oriented%20programming', 'Defecation', 'Feces', 'Perl%20Object-Oriented%20Persistence', 'Poop%20(constellation)', 'Poop%20deck', 'Pooper-scooper', 'Poopy', 'Stern', 'Zoboomafoo'];

function retrieveSummary(jsonp) {
console.log(jsonp);
}

function fetchSummary() {
for (var article in articleList) {
$.ajax({
url: 'https://en.wikipedia.org/w/api.php?action=parse&page=' + article + '&prop=text&format=json&section=0&callback=?',
dataType: 'jsonp',
contentType: 'application/json',
jsonpCallback: 'retrieveSummary',
});
}
}


The output I get is the jsonp object of 'Poop (constellation)', which is in the middle of the list. That's the only object I get, despite calling the callback function for each article in articleList.

Answer

Try something like this (untested):

var articleList = ['Abaft', 'Aspect-oriented%20programming', 'Defecation', 'Feces', 'Perl%20Object-Oriented%20Persistence', 'Poop%20(constellation)', 'Poop%20deck', 'Pooper-scooper', 'Poopy', 'Stern', 'Zoboomafoo'];

Promise.all(articleList.map(function(article) {
    return $.ajax({
        url: 'https://en.wikipedia.org/w/api.php?action=parse&page=' + article + '&prop=text&format=json&section=0&callback=?',
        dataType: 'jsonp',
        contentType: 'application/json',
    });
  })).then(function(results) {
    console.log(results);
});

The ajax call returns a promise, Promise.all waits until all promises are resolved then calls back.