SO 18660044 - xhr loops

http://stackoverflow.com/questions/18660044/how-to-deal-with-asyncronous-javascript-in-loops

by fiddlegrimbo

HTML

<pre id="results"></pre>

JavaScript

function log() {
    console.log.apply(console, arguments);
    var args = Array.prototype.slice.apply(arguments).map(function (it) {
        return "string" === typeof it ? it : JSON.stringify(it, null, 2);
    });
    document.getElementById("results").innerHTML += "\n" + args.join(", ");
}

function fakePhoneNumbers(prefix, count) {
    var numbers = [];
    for (var i = 0; i < count; i++) {
        numbers.push(prefix + "-" + i + "-number");
    }
    return numbers;
}

function phone(myperson, firstname) {
    this.myperson = myperson;
    this.firstname = firstname;
}

var globalCount = 0;
phone.prototype.get = function (cb) {
    var self = this;
    var ms = Math.floor(1000 * (Math.random() * 5));
    var firstname = this.firstname;

    var mycb = (function (id) {
        id = firstname + "-" + id;
        return function () {
            log("results for " + id + " after " + ms + " ms");
            var count = Math.floor(3 * Math.random());
            var phonenumbers = fakePhoneNumbers(id, count);
            cb(phonenumbers);
        };
    }(globalCount++));

    setTimeout(mycb, ms);
};

function callUntilTrue(cb) {
    var done = false;
    return function () {
        if (done) {
            log("previous callback succeeded. not calling others.");
            return;
        }
        var res = cb.apply(null, arguments);
        done = !! res;
    };
}

var myperson = {
    firstname: {
        "tom": null,
        "jerry": null,
        "micky": null
    },
    save: function () {
        log("save " + JSON.stringify(this, null, 2));
    }
};

var cb = function (myperson_, phonenumbers) {
    if (myperson_.phonearray) {
        log("person already has phone numbers. returning.");
        return false;
    }
    if (phonenumbers.length < 1) {
        log("response has no phone numbers. returning.");
        return false;
    }
    log("person has no existing phone numbers. saving ", phonenumbers);
    myperson_.phonearray = phonenumbers;
   ...