【问题标题】:What is the equivalent of this ternary operator expression?这个三元运算符表达式的等价物是什么?
【发布时间】:2020-10-16 22:18:08
【问题描述】:

我必须使用来自另一个公司项目的一段代码。 不幸的是,它包含一个在 SonarCloud 中触发错误的表达式。 错误是:

非空语句应该改变控制流或至少有一个副作用

写这行的同事已经不在公司了。

需要修改的行是xhr.status === 200 ? observable.next(xhr.response), observable.complete()) : observable.error(xhr.statusText);

这里是完整的代码:

  sendMedia(file: File, presignedUrl: string): Observable<Object> {
    return new Observable(observable => {
      const xhr = new XMLHttpRequest();
      xhr.open('PUT', presignedUrl, true);
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          xhr.status === 200 ?
            (observable.next(xhr.response), observable.complete()) :
            observable.error(xhr.statusText);
        }
      };
      xhr.send(file);
    });
  }

如果这个块等同于那个语句?

if (xhr.status === 200) {
  return observable.next(xhr.response), observable.complete();
} else {
  return observable.error(xhr.statusText);
}

非常感谢任何试图提供帮助的人!

【问题讨论】:

  • If this block equivalent to that statement?,您是否尝试过测试两者?
  • @ArnaudClaudel 我不能,我的项目没有测试单元。此外,如果我不理解代码,很难为它编写一个测试,这将包括我忽略的所有测试用例。
  • @sp00m 我完全同意你的看法!这段代码不是我写的,但我绝对不会这样做。
  • we do not have test units on my project 您可以使用您的应用程序简单地对其进行测试。 ---- Moreover, if I don't understand the code, it's hard to write a test for it 那么盲目地重构那段代码就更难了。 ---- that will include all the test cases that I ignore 这里只关注一条路径,不需要覆盖所有分支。

标签: javascript typescript comma conditional-operator


【解决方案1】:

除了return语句之外,你几乎就在那里

if (xhr.status === 200) {
  observable.next(xhr.response);
  observable.complete();
} else {
  observable.error(xhr.statusText);
}

【讨论】:

  • 感谢您的帮助!我不确定这些返回语句是否对我有帮助 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多