0

I'm only crawling in JS so probably the solution is obvious.

I'm writing a Chrome extension which in browser action (after clicking on extension's button) reads several pages and from each of them it retrieves an integer. Then, it creates a table with these integers. I'm doing it qith AJAX so it's asynchronous and I want to have all integers before creating the table.

I've read these topics:

...and wrote a code that doesn't work.

var sum = 0;

document.addEventListener('DOMContentLoaded', function () {
    var deferreds = [];
    var users = [...], pages = [...];
    for(i = 0; i < users.length; ++i) {
        for(j = 0; j < pages.length; ++j)
            deferreds.push(window[pages[j]](users[i], pages[j]));
    }
    $.when.apply(null, deferreds).done(function() {
        alert("sum: " + sum);
    });
});

function Name(user, page) {
    $.get("http://page2/" + user, function(data) {
        sum += 7;
    });
    return 7;
}

function Name2(user, page) {
    $.get("http://page/" + user, function(data) {
        sum += 84;
    });
    return 84;
}

So the alert prints 0 instead of 91. I cut the part with table as all fields are "undefined" anyway. If I get sum = 91, I'll probably get the table.

Community
  • 1
  • 1
user1
  • 945
  • 2
  • 13
  • 37

1 Answers1

0

As I said - obvious mistake. The functions should look like:

function Name(user, page) {
    return $.get("http://page2/" + user, function(data) {
        sum += 7;
    });
}
user1
  • 945
  • 2
  • 13
  • 37