管道和链条对我来说是新的......
我在让这个小脚本工作时遇到问题。我有一组需要用 AJAX 同步触发的 URL。在管道到下一次迭代之前,我需要等待每个 url 的成功响应(有些可能会延迟,因为它们将运行大型 SQL 查询和构建报告)。如果它没有成功,那么整个过程必须停止。
我想我已经很接近了,但你会发现它工作不正常。也许你们中的一位大师可以帮助我解决这个问题?
//counter
var i = 0;
//array of local urls that I need to trigger one after another
var arrValues = [
"http://fiddle.jshell.net/",
"http://fiddle.jshell.net/",
"http://fiddle.jshell.net/"];
//the step i need to repeat until done
var step = (function () {
//expect to see this alert called for each iteration (only happens once?)
alert(arrValues[i]+i);
var url = arrValues[i];
var model = {};
model.process = function () {
log('Starting: ' + url + i);
return $.ajax(url)
.done(function (jqXHR, textStatus, errorThrown) {
log(textStatus + ' ' + url + i + ' Done');
})
.fail(function (jqXHR, textStatus, errorThrown) {
log(textStatus + ' Failed');
});
};
return model;
}());
//just outputting to the div here
function log(message) {
$("#output").append($("<div></div>").text(message));
}
//start the process
log("Starting To Build Report");
//iterate through the array
$.each(arrValues, function (intIndex, objValue) {
// I need to wait for success before starting the next step or fail and throw
// the errors below - you will see this does not work now and never gets to the
// .done or .fail or .always
step.process().pipe( function () {
i++;
step.process();
});
}).done(function () {
log("The process completed successfully");
})
.fail(function () {
log("One of the steps failed");
})
.always(function () {
log("End of process");
});