管道和链接对我来说是新事物......
我在让这个小脚本正常工作时遇到问题。我有一个 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");
});
最佳答案
您已经快成功了,但细节非常重要。诀窍是:
- 修改
step
是一个函数(而不是一个对象),它返回一个函数,该函数本身返回一个可观察的对象(即 jqXHR Promise) - 允许
step
接受增量整数i
作为参数;这避免了维护运行i
的需要在外部范围内 - 建立一个
.then()
链与每个then()
将step()
返回的函数作为其参数 - 播种
.then()
具有已解决的 Promise 的链来启动它 - 附上最后的
.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");
});
关于JQUERY 与进程和管道的链接不适合我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15434691/