管道和链条对我来说是新的......
我遇到了让这个小脚本工作的问题。我有一组URL需要与AJAX同步触发。我需要等待每个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");
});
答案 0 :(得分:1)
你快到了,但细节非常重要。诀窍是:
step
修改为函数(不是对象),它返回一个函数,该函数本身返回一个可观察对象(即jqXHR承诺)step
接受增量整数i
作为参数;这样就无需在外部范围内维护运行i
.then()
链,每个then()
将step()
.then()
链播种以启动它.done()
,.fail()
,.always()
附加到then()
链的末尾。注意:从jQuery 1.8开始,我们不推荐使用.pipe()
,而是赞成修订后的.then()
。
以下是代码:
var arrValues = [
"http://fiddle.jshell.net/",
"http://fiddle.jshell.net/",
"http://fiddle.jshell.net/"
];
function step(i) {
return function() {
var url = arrValues[i];
log('Starting: ' + url + i);
return $.ajax(url).done(function(data, textStatus, jqXHR) {
log(textStatus + ' ' + url + i + ' Done');
}).fail(function(jqXHR, textStatus, errorThrown) {
log(textStatus + ' ' + url + i + ' Failed');
});
}
};
function log(message) {
$("#output").append($("<div/>").text(message));
}
log("Starting To Build Report");
var p = $.Deferred().resolve().promise();
$.each(arrValues, function(i, url) {
p = p.then(step(i));
});
p.done(function() {
log("The process completed successfully");
}).fail(function() {
log("One of the steps failed");
}).always(function() {
log("End of process");
});