How to avoid logic duplication when promisifying js methods?

丶灬走出姿态 提交于 2019-12-23 22:24:41

问题


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

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