这个”await”是不是一个不好的实践?

huangapple go评论54阅读模式
英文:

Is this await a bad practice?

问题

这段文本的翻译如下:

我看到一些代码检查工具指出了这种行为,但我想知道这是否部分原因是你会使用 promises:

const promise = myFn()
// 做其他事情
const result = myOtherFn(await promise)

错误:应该等待或捕获 promises

那么,这段代码是不正确的吗?如果是的话,为什么?

英文:

I have seen several linters flag this behaviour but I wonder if this isn't partially why you would use promises:

const promise = myFn()
//do other stuff
const result = myOtherFn(await promise)

> Error: promises should be awaited or catch

So is this an incorrect code? If so, why?

答案1

得分: 3

是的,这是对 await 的不寻常用法,也是一种可能导致应用程序崩溃的不良实践。

通常,你应该立即await这个Promise:

const value = await myFn()
// 做其他事情
const result = myOtherFn(value);

不立即await这个Promise的问题在于,当 // 做其他事情 正在运行时,你会错过它被拒绝并带有错误的情况。如果其他操作是异步的,你可能会太晚await它,如果其他操作本身抛出异常,你根本不会await它。在这两种情况下,都会导致promise未处理的拒绝,从而导致应用程序崩溃。请参考 https://stackoverflow.com/questions/46889290/waiting-for-more-than-one-concurrent-await-operationhttps://stackoverflow.com/questions/45285129/any-difference-between-await-promise-all-and-multiple-await

英文:

Yes, this is an unusual usage of await, and a bad practice that might cause your application to crash.

Normally you would immediately await the promise:

const value = await myFn()
// do other stuff
const result = myOtherFn(value);

The problem with not immediately awaiting the promise is that you will miss when it rejects with an error while the // do other stuff is running. If the other stuff is asynchronous, you may await it too late, if the other stuff throws an exception itself, you never await it, and in both cases this causes an unhandled rejection of the promise which will crash your application. See also https://stackoverflow.com/questions/46889290/waiting-for-more-than-one-concurrent-await-operation and https://stackoverflow.com/questions/45285129/any-difference-between-await-promise-all-and-multiple-await.

huangapple
  • 本文由 发表于 2023年5月29日 05:25:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定