【发布时间】:2021-06-01 17:33:02
【问题描述】:
我正在寻找一种方法来重构这种“如果 x 返回 x”模式。好像是多余的。
例如:
async exampleFunction(a) {
const firstResult = await this.firstHandler(a);
if (firstResult) {
return firstResult;
}
const secondResult = await this.secondHandler(a);
if (secondResult ) {
return secondResult;
}
const thirdResult = await this.thirdHandler(a);
if (thirdResult) {
return thirdResult;
}
}
【问题讨论】:
-
这很好 IMO,因为您希望该方法在收到
firstResult后立即停止。 -
更少的代码不等于更好的代码。你所拥有的东西很容易阅读,而且很有意义。除非你是故意打代码高尔夫,否则我认为这很好。
-
我不是在打代码高尔夫,但我有很多使用这种模式的函数调用
-
你可以做
const res=await a() || await b(); return res; -
是的,就是这样或工作方式