我有一些任务需要按顺序执行:
function doTasks(tasks, urlDoTask) {
// Create a deferred for each task by calling doTask().
var deferreds = $(tasks).map(function (i, task) {
return doTask(task, urlDoTask);
}).toArray();
// return a composite deferred which will wait for each of the doTask requests.
return $.when.apply($, deferreds);
}
function doTask(task, urlDoTask) {
return ajax({
url: getRootDir() + urlDoTask,
data: { param: task.SomeParam },
type: 'POST',
dataType: 'json'
}).then(function (data) {
return ok(createObject("status", "ok", "op", "doTask", "task", task, "data", "passed"));
},
function (data) {
return ok(createObject("status", "fail", "op", "doTask", "task", task, "data", "failed"));
});
}
function ok() {
return newPromise("resolve", arguments);
}
function newPromise(type, args) {
return $.Deferred(function (dfd) {
dfd[type].apply(dfd, args);
}).promise();
}
function createObject() {
var ob = {};
// copy all the arguments name/value pairs into the object
for (var i = 0; i < arguments.length; i += 2) {
var n = arguments[i];
var v = arguments[i + 1];
ob[n] = v;
}
return ob;
}
如何修改此代码以使每个 doTask 按顺序执行?我曾考虑过使用 jquery 队列,但如何在这里申请?也许做类似的事情:
var deferreds = $(tasks).map(function (i, task) {
$({}).queue(doTask(task, urlDoTask));
}).toArray();
并且一旦每个任务都完成了下一步()?