Zorken17 Zorken17 - 29 days ago 16
TypeScript Question

Wait for async .done() in every iteration of loop

So, I have function that locks like this:

function getMainData() {
var dfd = $.Deferred();

$.getJSON('My string that i pass',
function(result) {
if (result !== undefined) {
dfd.resolve(result);
}
})

return dfd.promise()
}

function getSpecificData() {
var dfd = $.Deferred();

var myArray = [];

for (var i = 0; i < 5; i++) {
getMainData().done(function(result) {
myArray.push(result)

dfd.resolve(myArray) //This is where I am lost.
})
}

return dfd.promise()
}

getSpecificData().done(function(result) {
console.log(result);
})


I think I know how promises work if you chain them together but I can not make the for-loop to wait for the async call to finish before the next iteration.

Can some please help me?

Answer

A for loop has no means of delaying the next iteration to wait for asynchronous code.

You can solve it by using a function that is called recursively instead

function getMainData() {
    return $.getJSON('My string that i pass');
}

function getSpecificData() {
    var myArray = [], def = new $.Deferred();

    (function rec(i) {
        getMainData().done(function(result) {
            myArray.push(result);
            if (i < 5 && result !== undefined) {
                console.log(i)
                rec(++i);
            } else {
                def.resolve(myArray);
            }
        });
    })(0);

    return def.promise();
}

getSpecificData().done(function(result) {
    console.log(result);
});