如何避免在if中分配变量

时间:2018-10-10 15:08:02

标签: javascript refactoring

给出以下代码段:

let a;
if (obj === undefined ||
    obj.prop === undefined ||
    (a = await getResultFromLongOperation(obj.prop)) === undefined) {

    // Do things to handle the case where the params were wrong and throw an error

}
console.log(a); // a is not undefined

我想避免在if内部分配a的值。
但我也不想多次致电getResultFromLongOperation,也不想重复“处理参数错误的情况”。

我该如何重构?

我发现的唯一解决方案是重构:

function doThingsToHandleTheCaseTheParamsAreWrong() {
    // Do things to handle the case where the params were wrong and throw an error
}

if (obj === undefined ||
    obj.prop === undefined) {
    doThingsToHandleTheCaseTheParamsAreWrong();
}

let a = getResultFromLongOperation(obj.prop);

if (a === undefined) {
    doThingsToHandleTheCaseTheParamsAreWrong();
}

console.log(a); // a is not undefined

这真的好吗?

1 个答案:

答案 0 :(得分:0)

在您的情况下,此构造是否可以工作:

const a = getResultFromLongOperation(obj.prop) || doThingsToHandleTheCaseTheParamsAreWrong();

取决于a是否可以返回undefined的其他虚假值。

const tmpA = getResultFromLongOperation(obj.prop);
const a = tmpA !== undefined ? tempA : doThingsToHandleTheCaseTheParamsAreWrong();