How to create a Promise with default catch and then handlers

谁说我不能喝 提交于 2019-12-11 04:45:42

问题


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
});


来源:https://stackoverflow.com/questions/38194127/how-to-create-a-promise-with-default-catch-and-then-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!