为什么没有调用Deferred.fail?

时间:2015-05-11 07:05:50

标签: jquery promise

我已阅读this article关于 jQuery延迟不符合Promise / A + 的事实

这导致我测试代码(应该引发错误而不传播到主窗口并停止运行,他们建议使用相似的代码,但我想尝试使其更简单 - 因此我的问题) :

var def = new jQuery.Deferred();
var bar = def.then(function (rslv) {

 try {
    throw Error('Exception!');
 }
 catch (e) {

    def.reject();
 }

 return def.promise();
});

bar.fail(function (val) { //why doesn't this line run ?
 console.log('Exception thrown and handled');
});
def.resolve();

console.log(1)

问题:

def.then(...)会返回保留在bar

中的承诺

bar - 失败时 - 应该运行:

  bar.fail(function (val) {
     console.log('Exception thrown and handled');
    });

但它没有运行。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

尝试在已解决的load的初始bar内重新定义bar = def.then(success, error)。在defcatch设置为新bar,以jQuery.Deferred()为参数调用reject,返回" new" e,应在bar.promise()致电error;并允许bar.then(success, error)被"链接"到jQuery promise方法



bar

var def = new jQuery.Deferred();

var success = function success(data) {
  console.log("success", data)
};

var error = function error(val) { //why doesn't this line run ?
 console.log('Exception thrown and handled', val, val.message);
};

var bar = def.then(function (rslv) {
 // `success`
 console.log("rslv", rslv);
 try {
    throw Error('Exception!');
 }
 catch (e) {
    // return rejected jQuery promise,
    // having `e` reason
    bar = jQuery.Deferred().reject(e);
    
 };
 // call `error` ,
 // return `bar` jQuery promise `Error('Exception!')`,
 // for "chaining" jQuery promise methods
 return bar.promise()
});

// call `success`, call `error`
bar.then(success, error);

def.resolve("success");

console.log(1);