我想做一个同步的 web 服务调用,然后是几个并行调用,并在并行任务完成时完成最终的同步调用。我一直在研究 $.Deferred 并从概念上理解它,但找不到正确的语法来做到这一点。我知道这段代码中有许多错误会尝试进行三个连续调用。checkProgress 代码永远不会被调用。
function doSequential(a, b, c) {
report("Starting Sequential Test");
process("A", urlDo, a, '#spnA');
process("B", urlDo, b, '#spnB');
process("C", urlDo, c, '#spnC');
}
function process(id, url, size, selector) {
var data = JSON.stringify({ id: id, size: size });
var deferred = $.Deferred();
deferred.promise = $.ajax({
url: urlDo,
data: data,
type: "Post",
contentType: 'application/json; charset=utf-8',
dataType: "json"
});
deferred.then(
function (response) {
// Done
$("#spn" + id).append("Done");
report(id + " done");
return
},
function (error) {
// Fail
$("#spn" + id).append("Error: " + error);
report(id + " error: " + error);
return;
},
function (data) {
// Notify progress
var check = setInterval(function () {
var done = checkProgress(id);
if (done) {
clearInterval(check);
return;
}
}, 1000);
return;
});
}
function checkProgress(id) {
var data = JSON.stringify({ id: id });
var status = ajaxCall(urlCheck, data);
if (status) {
$("#status" + id).text(status.count + " of " + status.size);
report(status.message);
return status.done;
}
report("checkProgress failed");
return true;
}