2013-09-24 38 views
1

我們都熟悉the $.Deferred() behaviour當它成功和失敗:遞延當返回備份失敗

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 the function 
$.when(foo()) 
    .always(function(something) { 
     // 'something' is either data, OR jqXHR, depending if the thing fails 
    }); 

不過,我的data,被稱爲backup備份結果,居住功能foo裏面,那我d希望在請求失敗時返回。

只要我能在$.ajax(...)設置爲既不改變參數(這意味着我不能添加一個「失敗」的處理程序),也無法改變的foo返回類型,也不是外foo移動backup,我怎麼能達到以下效果?

function foo() { 
    var backup = 'bar', 
     dfd = $.ajax(...) 
     .done(function(data, textStatus, jqXHR) { 
      alert(data); 
     }) 
     .fail(function(jqXHR, textStatus, errorThrown) { 
      // replace return with 'bar', which is impossible 
      // because 'data' is undefined 
      data = backup; 
     }); 

    return dfd.promise(); 
} 

// outside the function 
$.when(foo()) 
    .always(function(something) { 
     // 'something' is now some fresh data, or 'bar' if ajax fails 
    }); 

回答

1

創建自己的遞延對象,而不是使用$.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) { 

}); 
+0

就像一個魅力。謝謝你的提示! – Brian