4

I have an error in SonarQueb that says

Refactor this redundant 'await' on a non-promise.

Below is my JS code. Is the await really redundant? What would be the 'correct' non-redundant code (that keeps the same functionality)? Just remove await?

async getNavLink(name: string) {
    console.log(`getNavLink ${name}`);
    return await element(by.cssContainingText('.navigation li span', name));
}
user1142130
  • 1,617
  • 3
  • 20
  • 34
  • that depends on what the code called post `await` does, i guess its internally Async implemented – Mrinal Kamboj Aug 20 '19 at 14:35
  • if the `element` function doesn't return a promise, then `await` makes no actual difference and removing it will be inconsequential. – VLAZ Aug 20 '19 at 14:44
  • TL;DR: Sonar was wrong, the rule has been removed from the default ruleset. Always use `return await asyncFn(...)`, never skip await. – Tamas Hegedus Nov 10 '22 at 18:11

1 Answers1

1

In short: Sonar was wrong, you never skip that await in return await asyncFn();.

There used to be a performance benefit argument, there also used to be people saying it is the same anyway so why don't we spare those 6 keystrokes?

But towards the end of 2022 the industry is slowly arriving at an understanding that this rule was a bad idea.

The performance claims were shown to be false: Are there performance concerns with `return await`?

And also it turns out it is not the same. By skipping await an enclosing try-catch will not catch the errors and an enclosing try-finally will not wait for the promise, so the finally block will run sooner than expected.

It is planned to remove the rule from the default ruleset: https://community.sonarsource.com/t/await-should-not-be-used-redundantly/29074/8

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97