在宣传js方法时如何避免逻辑重复?

时间:2016-12-07 16:03:19

标签: javascript typescript promise method-chaining

最近我接受了承诺链式模式。这样做很方便:

action1
.then(()=> action2())
.then(()=> action3());

但是,为了做到这一点,我改变了我的所有方法(TypeScript):

action1() : Promise<any>{
  try{
     // actual code
     return Promise.resolve();
  } catch (err){
     console.error(err);
     return Promise.reject(err);
  }
}

这看起来非常重复。什么是避免代码重复的最佳方法?

2 个答案:

答案 0 :(得分:2)

编写一个函数来包装一个函数的promise,你可以重用它

<parent-component>
    <child-component></child-component>
    <child-component></child-component>
    <child-component></child-component>
    <child-component></child-component>
    <child-component></child-component>
</parent-component>

答案 1 :(得分:0)

由于您使用的是打字稿,因此您需要使用async/await。只需做

async action1(): Promise<any>{
  try {
     return // actual code;
  } catch (err){
     console.error(err);
     throw err;
  }
}

然而,您很可能实际上不想捕获,记录和重新抛出每个函数中的所有错误,因此这简化为

async action1(): Promise<any>{
  return // actual code;
}
相关问题