Reputation: 1339
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.
Upvotes: 1
Views: 3604
Reputation: 276396
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
});
Upvotes: 2