如何使用默认捕获和处理程序创buildPromise
我正在创build一个使用koa和babelasynchronous/等待的API
我的控制器函数中的每一个承诺看起来像这样
async function ... { await Promise ... .then(data => response function) .catch(err => err function) }
每个承诺都有完全相同的响应和错误function。
有没有办法让我自动地使用相同的then / catch解决每个承诺(就像promise的默认parsing函数一样)。
然后我的代码看起来像这样:
async function ... { await Promise ... }
承诺会自动解决/捕获。
使用组成:
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); } }
哪个可以让你做到:
new MyPromise((resolve, reject) => {... }).then(() => { // default actions have already run here });