1

I am fairly used to seeing promises handled in the then/catch style in TypeScript, such as:

.findById(id)
.then((result: something | undefined) => result ?? dosomething(result))
.catch((error: any) => console.log(error))

However I also see the pattern where void is used to prevent the floating promise and indeed it is sometimes recommended by my language server as a fix.

void somePromise().dosomething();

Now, I'm not particularly versed in TypeScript or promises at all but I'm struggling to see how it would ever be preferable to skip using catch and simply use void. Brief googling didn't give me any clear distinction on when to do what.

There is this other answer explaining what void does, but not why I would want to use it. And there are various questions relating to solving floating promises but none that I could find detailing why I would take the void approach over catch.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
axwr
  • 2,118
  • 1
  • 16
  • 29
  • So no chance for `async/await`? – Anatoly Dec 16 '20 at 19:31
  • 1
    [You should indeed never skip the `.catch()`](https://stackoverflow.com/q/32384449/1048572) (if you can't be 100% certain that the promise will never reject). Using `void` is just a hack to satisfy the linter. – Bergi Dec 16 '20 at 21:59
  • If you are *truly* never interested in the result of an async operation, then `void` can be used. So, in a sense, it's *valid*. However, not wanting to know whether something succeeded or failed is quite rare. I can't quite think of any examples right now. – VLAZ Dec 17 '20 at 08:37

1 Answers1

2

Adding void here doesn't really alter the behavior of your program, so the only reason this could be mentioned is as a sort of 'shut up' operator, e.g.: a means to quiet your linter.

Evert
  • 93,428
  • 18
  • 118
  • 189