jQuery.ajax多任务异步转同步示例

let tasks = []; //任务列表
let counter = 0; //计数器

//任务
let todo = function(){
    if(counter<tasks.length){
        $.ajax({
            url: "/test.ashx",
            data: "task=" + tasks[counter],
            async: true,
            success: function(data){
                console.log(data);
            },
            error: function(){
                console.log("error.");
            },
            complete: function(){
                console.log(counter, tasks.length);
                counter++;
                todo();
            }
        });
    }else{
        console.log("finish.");
    }
}

//初始化任务列表和计数器,开始任务
$("#btn").click(function(){
    tasks = ["task1", "task2", "task3"];
    counter = 0;
    todo();
});



评论: 0 | 引用: 0 | 查看次数: 715
发表评论
登录后再发表评论!