如何使用默认catch和处理程序创建Promise [英] How to create a Promise with default catch and then handlers
本文介绍了如何使用默认catch和处理程序创建Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个使用koa和babel async/await的API
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)
}
每个promise具有完全相同的响应和错误功能.
Each promise has the exact same response and error function.
有没有办法让我用相同的then/catch自动使每个promise解析(就像promise的默认resolve函数一样).
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).
然后我的代码如下:
async function ... {
await Promise ...
}
并且诺言将自动解决/捕获.
and the promise would auto resolve/catch.
推荐答案
使用组成:
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
});
这篇关于如何使用默认catch和处理程序创建Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文