jQuery Deferred - catch vs fail

时间:2015-12-16 17:48:52

标签: javascript jquery promise jquery-deferred deferred

我想确保我没有错过任何一招;在Kris Kowal的库中,您可以在promises中执行以下通用catch语句:

var a, b, c, d, e, f;

readFile('fileA')
    .then(function (res) {
        a = res;

        return readFile('fileB');
    })
    .then(function (res) {
        b = res;

        return readFile('fileC');
    })
    .then(function (res) {
        c = res;

        return readFile('fileD');
    })
    .then(function (res) {
        d = res;

        return readFile('fileE');
    })
    .then(function (res) {
        e = res;

        return readFile('fileF');
    })
    .then(function () {
        f = res;
    })
    .catch(function () {
        // error happened in file read *somewhere* (don't care where)
    });

在jQuery的延迟对象中,没有catch语句,相反,我必须这样做:

var a, b, c, d, e, f;

readFile('fileA')
    .then(function (res) {
        a = res;

        return readFile('fileB');
    })
    .fail(function () {
        // error happened in file read *somewhere* (don't care where)
    })
    .then(function (res) {
        b = res;

        return readFile('fileC');
    })
    .fail(function () {
        // error happened in file read *somewhere* (don't care where)
    })
    .then(function (res) {
        c = res;

        return readFile('fileD');
    })
    .fail(function () {
        // error happened in file read *somewhere* (don't care where)
    })
    .then(function (res) {
        d = res;

        return readFile('fileE');
    })
    .fail(function () {
        // error happened in file read *somewhere* (don't care where)
    })
    .then(function (res) {
        e = res;

        return readFile('fileF');
    })
    .fail(function () {
        // error happened in file read *somewhere* (don't care where)
    })
    .then(function (res) {
        f = res;

        return readFile('fileF');
    })
    .fail(function () {
        // error happened in file read *somewhere* (don't care where)
    });

不幸的是,每个then分支都有独特的逻辑。我是否遗漏了某些内容,或者jQuery变体是否超出了在Kris Kowal的q库中实现等效的唯一方法?

1 个答案:

答案 0 :(得分:3)

假设readFile返回一个promise对象,你实际上可以使用$.when()异步加载所有文件(如果你不关心文件的读取顺序,那么的cource ):

来自文档:

  

在将多个Deferred对象传递给jQuery.when()的情况下,该方法从新的“master”Deferred对象返回Promise,该对象跟踪已传递的所有Deferred的聚合状态。所有延期解决方案解决后,该方法将解决其主延期,或者一旦拒绝其中一个延期,拒绝主延期。如果解析了主延迟,则执行主延迟的doneCallbacks。传递给doneCallbacks的参数为每个Deferreds提供已解析的值,并匹配Deferreds传递给jQuery的顺序.when()

强调我的

$.when(readFile('fileA'), readFile('fileB'), readFile('fileC'), readFile('fileD'), readFile('fileE'), readFile('fileF'))
.then(function(a, b, c, d, e, f) {
    // big success
},function() {
    // error happened in file read *somewhere* (don't care where)
});