1

I've read this article about the fact that jQuery deferreds are not Promise/A+ compliant

Which leads me to test a code (which should raise error without propagating to main window and stop running , they suggested similar code , but I wanted to try and make it simplier - hence my question):

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)

Question:

def.then(...) returns a promise which is kept in bar

bar - when failed - should run :

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

But it is not running.

What am I missing?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

0

Try redefining bar within initial bar = def.then(success, error) of resolved def . At catch set bar as new jQuery.Deferred(), calling reject with e as parameter , returning "new" bar.promise() , which should call error at bar.then(success, error) ; and allow bar to be "chained" to jQuery promise methods

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
guest271314
  • 1
  • 15
  • 104
  • 177