jQuery Deferred - catch vs fail

jQuery Deferred - catch vs fail

本文关键字:vs fail catch Deferred jQuery      更新时间:2023-09-26

我想确保我没有错过任何技巧;在Kris Kowal的库中,您可以在promise中作为通用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库中实现等效功能的唯一方法?

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

来自文档:

在将多个Deferred对象传递给jQuery.when()的情况下,该方法从一个新的"主"Deferred object返回Promise,该对象跟踪已传递的所有Deferred的聚合状态。一旦所有Deferred都被解析,该方法就会解析其主Deferred,或者一旦其中一个Deferred被拒绝,就会拒绝主Deferred。如果解析了主机Deferred,则会执行主机Deferrd的doneCallbacks。传递给doneCallbacks的参数为每个Deferred提供解析的值,并与Deferred传递给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)
});