How to create a Promise with default catch and the

2019-08-04 22:14发布

问题:

I'm creating an API that is using koa and babel async/await

Every promise in my controllers function looks like this:

async function ... {
    await Promise ... 
       .then(data => response function)
       .catch(err => err function)
}

Each promise has the exact same response and error function.

Is there a way for me to automatically have each promise resolve with the same then/catch (like a default resolve function for the promise).

Then my code would look like this:

async function ... {
    await Promise ... 
}

and the promise would auto resolve/catch.

回答1:

Use composition:

class MyPromise {
    constructor(executor) {
       this.promise = new Promise(executor);
       this.promise = this.promise
                          .then(defaultOnFulfilled, defaultOnReject);
    }
    then(onFulfilled, onRejected) {
       return this.promise.then(onFulfilled, onRejected);
    }
    catch(onRejected) {
       return this.promise.catch(onRejected);
    }
}

Which would let you do:

new MyPromise((resolve, reject) => {... }).then(() => {
   // default actions have already run here
});