【问题标题】:typescript - custom method off Promisetypescript - 关闭 Promise 的自定义方法
【发布时间】:2018-12-14 09:43:59
【问题描述】:

我已经声明了一个返回 promise 的方法:

confirm(title: string, message: string) {
    var promise = new Promise((resolve, reject) => {

        ....

        if (success) {
            resolve();
        } else {
            reject();
        }
    });
    return promise;
}

使用它的唯一方法似乎如下

confirm(...).then(() => { /*success code*/ }, () => { /*error code*/ });

为了简单起见,我想介绍自定义回调,但不太确定如何去做。

这就是我的意思 - 将 .then 拆分为两种方法:

confirm(...)
  .done(() => { })
  .fail(() => { });

有人对如何实施有建议吗?或者至少我可以在哪里谷歌解决方法?

【问题讨论】:

    标签: typescript promise extension-methods deferred


    【解决方案1】:

    据我所知,您提出的方法等同于thencatchthen 也接受拒绝回调,但不是必须):

    confirm("", "")
        .then(()=> {})
        .catch(()=> {})
    

    如果你真的想添加这样的别名,你可以将 then 添加到 prototype,但你必须声明它们以便 typescript 知道这一点:

    declare global { // declare global { ... } needed if we are in a module, otherwise just the content of this block is needed
        interface Promise<T> {
            done(done : () => void): Promise<void>//overly simplistic, should be oveloded if we want this to be general propose
            fail(done : () => void): Promise<void>//overly simplistic, should be oveloded if we want this to be general propose
        }
    }
    
    Promise.prototype.done  =Promise.prototype.then;
    Promise.prototype.fail  =Promise.prototype.catch;
    
    confirm("", "")
        .done(()=> console.log("ok"))
        .fail(()=> console.log("fail"))
    

    您也可以使用 async/await 来处理 Promise,也许它更适合您的情况:

    (async function () {
        try {
            await confirm('', '');
            console.log('ok')
        } catch (e) {
            console.log('fail')
        }
    })()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多