有沒有辦法爲承諾提供默認的errorCallback,例如,如果用戶提供了errorCallback,則默認的errorCallback會調用而不是。是否有可能爲承諾提供默認的errorCallback?
function getFoo() {
// TODO magic goes here to setup defaultErrorCallback as default
return $http.get("/not_exists");
};
function defaultErrorCallback() { console.log("DDD"); }
function customCallback() { console.log("CCC"); }
getFoo().then(fooSuccess);
// output: DDD
getFoo().then(fooSuccess, customCallback);
// output: CCC
爲什麼要這樣?通常情況下,你只需在你的承諾鏈的末尾添加'.catch(finalErrorCallback)',但看起來你想在'getFoo()'中添加處理程序(我認爲這是不可能的)。 – gyre
這有點像問,有沒有辦法讓我的代碼捕獲它自己的錯誤,但只有當沒有人把它放入try-catch?這似乎不是一個非常明智的設計。 – JLRishe
@gyre - 爲什麼?主要是因爲我有大量的代碼庫,有很多調用這個getFoo,不想重複getFoo()。然後(fooSuccess,defaultErrorCallback);.我們的defaultErrorCallback需要注入alertService,這對於這個樣板代碼來說也是非常煩人的。 –