jquery - Return backup when deferred fails -
we familiar the $.deferred()
behaviour when succeeds , fails:
function foo() { var backup = 'bar', dfd = $.ajax(...) .done(function(data, textstatus, jqxhr) { alert(data); }) .fail(function(jqxhr, textstatus, errorthrown) { alert(errorthrown); }); return dfd.promise(); } // outside function $.when(foo()) .always(function(something) { // 'something' either data, or jqxhr, depending if thing fails });
however, have backup result of data
, known backup
, residing inside function foo
, i'd return when request fails.
provided can neither change parameters set in $.ajax(...)
(meaning cannot add "fail" handler), nor change return type of foo
, nor move backup
outside foo
, how can achieve following effect?
function foo() { var backup = 'bar', dfd = $.ajax(...) .done(function(data, textstatus, jqxhr) { alert(data); }) .fail(function(jqxhr, textstatus, errorthrown) { // replace return 'bar', impossible // because 'data' undefined data = backup; }); return dfd.promise(); } // outside function $.when(foo()) .always(function(something) { // 'something' fresh data, or 'bar' if ajax fails });
create own deferred object, instead of using 1 returned $.ajax()
:
function foo() { var def = $.deferred(); var backup = 'bar'; $.ajax(...) .done(function(data, textstatus, jqxhr) { def.resolve(data); }) .fail(function(jqxhr, textstatus, errorthrown) { def.resolve(backup); }); return def.promise(); }
...
foo().done(function(data) { });
Comments
Post a Comment