问题
Recently I embraced promises chaining pattern. It's very convenient to do like this:
action1
.then(()=> action2())
.then(()=> action3());
But, in order to do it I changed all my methods like this (TypeScript):
action1() : Promise<any>{
try{
// actual code
return Promise.resolve();
} catch (err){
console.error(err);
return Promise.reject(err);
}
}
This looks like very repetitive pattern. What's the best way to avoid code duplication?
回答1:
Write a function to wrap promise over a function and you can reuse it
wrapPromise(fun) : Promise<any>{
try{
var value = fun()
return Promise.resolve(value);
} catch (err){
console.error(err);
return Promise.reject(err);
}
}
wrapPromise(action1).then()
回答2:
Since you are using typescript, you'll want to use async/await. Simply do
async action1(): Promise<any>{
try {
return // actual code;
} catch (err){
console.error(err);
throw err;
}
}
However there's a good chance you actually don't want to catch, log and rethrow all errors in every function, so this simplifies to
async action1(): Promise<any>{
return // actual code;
}
来源:https://stackoverflow.com/questions/41022004/how-to-avoid-logic-duplication-when-promisifying-js-methods