简体   繁体   English

避免 TypeScript 中的浮动承诺。 Void vs.catch 什么时候? 为什么?

[英]Avoiding Floating Promises in TypeScript. Void vs .catch When? Why?

I am fairly used to seeing promises handled in the then / catch style in TypeScript, such as:我相当习惯于在 TypeScript 中看到以then / catch样式处理的承诺,例如:

.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 来防止浮动 promise 的模式,实际上我的语言服务器有时会推荐它作为修复。

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.现在,我并不特别精通 TypeScript 或承诺,但我正在努力了解如何最好跳过使用 catch 并简单地使用 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.还有另一个答案解释了 void 的作用,但不是我为什么要使用它。 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.还有很多关于解决浮动承诺的问题,但我找不到详细说明为什么我会采用 void 方法而不是 catch 的原因。

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, eg: a means to quiet your linter.在此处添加void并不会真正改变程序的行为,因此可以提及的唯一原因是作为一种“闭嘴”运算符,例如:一种使 linter 安静的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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