简体   繁体   English

如何循环遍历一组异步作业,并分别执行它们?

[英]How to loop through an array of asynchronous jobs, and do them respectively?

There is an array of jobs, say 'asking user to fill a form', 'issue an ajax request', etc. 有一系列工作,比如“要求用户填写表格”,“发出ajax请求”等。

I need to run these jobs one after another and finally call a complete() method. 我需要一个接一个地运行这些作业,最后调用一个complete()方法。

Something like: 就像是:

var jobs = [11, 22, 33, 44, ...];

for(var i = 0; i < jobs.length; i++) {
   alert('Starting job #' + i);

   // chooseJobOperator shows a form and wait for user to <select> a member
   // and click save <button>
   async(chooseJobOperator(jobs[i]));

   alert('Job #' + i + ' is done, now for-loop will continue');
}

alert('All jobs are done now.');
complete();

When my job is for example showing a prompt() I don't need to do anything, since prompt is a synchronous method, but what about asynchronous methods? 当我的工作是例如显示一个prompt()我不需要做任何事情,因为prompt是一个同步方法,但异步方法呢?

Is it possible to do so using jQuery.Deffered ? 是否可以使用jQuery.Deffered这样做?

You can try this 你可以试试这个

var jobs = [11, 12, 14, 15];
function doTheJob() {
    if (jobs.length === 0) {
        alert('All jobs are done now.');
        complete();
        return;
    }

    var job_Id = jobs.pop();
    $.ajax({
        url: "/DoTheJob",
        complete: function () {
            doTheJob();
        }
    });
};

Maybe there is better approach, but I would use $.when function for this. 也许有更好的方法,但我会使用$.when函数。 Here is an example of how it could look: 以下是它的外观示例:

var jobs = [1, 2, 3];

var d = $.Deferred(),
    stack = [];

for (var i = 0; i < jobs.length; i++) {
    stack.push(async(jobs[i]));
}

$.when.apply($, stack).done(function() {
    alert('All done');
});

function async(type) {
    alert('Starting job #' + type);
    return $.Deferred(function() {
        var self = this;
        setTimeout(function() {
            alert('Job #' + type + ' is done');
            self.resolve();
        }, 1000 * type);
    });
}

I used setTimeout as asynchronous operation. 我使用setTimeout作为异步操作。

http://jsfiddle.net/rs3Qv/1/ http://jsfiddle.net/rs3Qv/1/

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

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