鍍金池/ 問答/HTML/ 如何繼承promise,并為resolve和reject添加新的方法

如何繼承promise,并為resolve和reject添加新的方法

因為正常調(diào)用會需要重復(fù)的寫大量的頁面提示

Api().then(()=>{
        showLoading()
        
        dosomething()
    }).catch(()=>{
        showfail()
        
        dosomething()
    })

想實現(xiàn)

class mPromise extends Promise{
    //...

}

之后把原來 return new Promise 改成 return new mPromise

就可以在 thencatch 的邏輯里不用寫 showLoading()showfail()

請問繼承里該怎么寫呢?

或者如果用裝飾者模式又怎么寫呢?

回答
編輯回答
不二心

@說好的一血呢 的答案挺有意思,我來做個翻譯,哈哈哈,請大佬不要見怪,因為對Promise chain自己也不熟。所以作如下嘗試:
請看如下圖

clipboard.png

2017年10月16日 06:04
編輯回答
墨小白

類似于實現(xiàn) Promise.finally

Promise.prototype.finally = function (callback) {
  let P = this.constructor
  return this.then(
    value  => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  )
}
2017年6月21日 14:12
編輯回答
我以為

這個是偽需求。

要實現(xiàn)這樣的效果根本不需要這么復(fù)雜!

下面這一個簡短的代碼就可以實現(xiàn)。

// 定義一個基api
const baseApi = (url, options) => Api(url, options).then(showLoading).catch(err => {
    showFail(err)
    throw err
})
// 使用   
baseApi('你的url', {}).then(dosomething).catch(dosomething) 

希望我的回答可以幫助到你,謝謝~

2018年7月1日 14:44