英文:
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-operation 和 https://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 await
ing 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论