Search code examples
typescriptpromiseextension-methodsdeferred

typescript - custom method off Promise


I've declared a method that returns promise:

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

        ....

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

The only way to work with it seems to be as follows

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

I'd like to introduce custom callbacks for simplicity but not quite sure how to go about it.

Here's what I mean - splitting .then into two methods:

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

Does anyone have suggestions on how to implement it? Or at least where I can google workarounds?


Solution

  • The methods you propose are equivalent to then and catch from what I can tell (then also accepts a rejection callback but it does not have to):

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

    If you really want to add such aliases you can add then to the prototype, but you must declare them so that typescript knows about this:

    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"))
    

    You can also use async/await to work with the promise, maybe it's works better for your case:

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