简体   繁体   English

在Jquery中,如何延迟由异步调用组成的同步函数的执行?

[英]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. “准备”完成后,我需要执行功能“ testit”。 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. 创建一个延迟的对象,该对象在所有ajax请求完成时进行解析。

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: 你可以把testit在Ajax请求的成功功能prepareit ,就像这样:

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). 我想说,循环ajax请求不是执行此操作的最佳方法-如果可能,您应该更改代码以在ajax调用中传递整个列表,而不是多次循环(不确切知道您要完成的工作)课程)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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