简体   繁体   中英

In Jquery, how to delay execution of an synchronous function that consist on asynchronous calls?

i'm confused. In case of this code:

function prepareit(list){
    for(i=0;i<list.length;i++){
         var test = list[i];
         $.ajax({....});
    }
}

function testit(list){
    for(i=0;i<list.length;i++){
         var test = list[i];
         $.ajax({....});
    }
}

$(document).ready(function() {
    var list = ['ti','meti','medes','fra','u','w','ro','sit','hd','i'];
    prepareit(list);
    testit(list);
});

I need to execute function "testit" when "prepareit" has complete. I've already tried with "when-then" method but functions start at same time.

(sorry for my bad english)

Create a deferred object that resolves when all of the ajax requests are done.

function prepareit(list){
    var defArr = [];
    for(i=0;i<list.length;i++){
         var test = list[i];
         defArr.push($.ajax({....}));
    }
    return $.when.apply($,defArr);
}

function testit(list){
    var defArr = [];
    for(i=0;i<list.length;i++){
         var test = list[i];
          defArr.push($.ajax({....}));
    }
    return $.when.apply($,defArr);
}

$(document).ready(function() {
    var list = ['ti','meti','medes','fra','u','w','ro','sit','hd','i'];
    prepareit(list).done(function(){
        testit(list).done(function(){
            alert("All done!");
        });
    });
});

You could call testit in the success function of the ajax request in prepareit , like so:

function prepareit(list){
    for(i=0;i<list.length;i++){
         var test = list[i];
         $.ajax({ success: function (data) { testit(list); } });
    }
}

function testit(list){
    for(i=0;i<list.length;i++){
         var test = list[i];
         $.ajax({....});
    }
}

$(document).ready(function() {
    var list = ['ti','meti','medes','fra','u','w','ro','sit','hd','i'];
    prepareit(list);
    //testit(list);
});

However, this won't work if you depend on the entire list being "prepared" before "testing". I'd say that looping ajax requests is not the best way to do this - if possible you should change your code to pass the entire list in the ajax call rather than looping multiple times (not knowing exactly what you're trying to accomplish of course).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM