简体   繁体   中英

What is the equivalent of this ternary operator expression?

I have to use a piece of code that comes from another company project. Unfortunately, it contains an expression that triggers an error in SonarCloud. The error is:

Non-empty statements should change control flow or have at least one side-effect

The colleague that wrote this line is not in the company anymore.

The line that needs to be modified is xhr.status === 200? observable.next(xhr.response), observable.complete()): observable.error(xhr.statusText); xhr.status === 200? observable.next(xhr.response), observable.complete()): observable.error(xhr.statusText); .

Here is the full code:

  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 this block equivalent to that statement?

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

Thanks a lot for anyone trying to help!

You are almost there except return statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM