Wait a few ajax finished, but the ajax function is dynamically called

4058 views javascript
6

I want to wait a few ajax finished. I have checked some pages and get the ideas of

$.when ().done(funciton(){})....

However in my case is little bit complex. ajax is dynamically generated and, it is the method of the Class.

class TestClass{
    constructor(){} 
    myAjax = function(id){
        $.ajax({
            url:  myajax,
            type: 'POST',dataType: 'json',
            data: {"id" : id},
            success: function(data) {
                console.log("byId loaded:"+ id);
            }
        });
    }
}
testclass = new TestClass();
var myIds = [1,3,5,7];
for (var i in myIds) {
    testclass.myAjax(myIds[i]); // I want to wait every ajax is finished.
}

I have tried like this using $.when() but in vain (compile error)

$.when(
for (var i in myIds) {
    testclass.callGraph(myIds[i]); .

).done(function(){
    console.log("load finished");
}

answered question

Classes and jQuery? Not great mix. Right time for fetch() and Promise.all().

1 Answer

3

Try this

class TestClass{
    constructor(){} 
    myAjax = function(id){
        return $.ajax({
            url:  myajax,
            type: 'POST',dataType: 'json',
            data: {"id" : id},
            success: function(data) {
                console.log("byId loaded:"+ id);
            }
        });
    }
}
testclass = new TestClass();
var promises = [];
var myIds = [1,3,5,7];
for (var i in myIds) {
    promises.push(testclass.myAjax(myIds[i])); // I want to wait every ajax is finished.
}

$.when(promises).then(function(values){
   console.log('all ajax request completed');
});

posted this

Have an answer?

JD

Please login first before posting an answer.