2

JSF中间代码

管道和链条对我来说是新的......

我在让这个小脚本工作时遇到问题。我有一组需要用 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");
});
4

1 回答 1

1

你快到了,但细节是最重要的。诀窍是:

  • 修改step为一个函数(不是一个对象),它返回一个函数,该函数本身返回一个可观察的对象(即一个 jqXHR 承诺)
  • 允许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");
});

更新的小提琴

于 2013-03-15T21:22:45.987 回答