“返回等待"是否存在性能问题? [英] Are there performance concerns with `return await`?
问题描述
我看到有一个 eslint 规则,no-return-await
,用于禁止return await
.
I see there is an eslint rule, no-return-await
, for disallowing return await
.
在规则的描述中,它声明 return await
添加 在总体 Promise 解决或拒绝之前的额外时间"
.
In the rule's description, it states a return await
adds "extra time before the overarching Promise resolves or rejects"
.
但是,当我查看 MDN async
函数文档,简单示例"显示了一个包含 return await
的示例,但没有说明这可能是性能问题的原因.
However, when I look at MDN async
function docs, the "Simple Example" shows an example containing return await
without any description of why this might be a performance problem.
return await
是 eslint 文档建议的实际性能问题吗?
Is return await
an actual performance problem as the eslint docs suggest?
如果是,怎么办?
推荐答案
不,没有任何性能问题.这只是一个不必要的额外操作.执行可能需要更长的时间,但应该几乎不会引起注意.对于整数x
,它类似于return x+0
而不是return x
.或者更确切地说,完全等同于毫无意义的.then(x => x)
.
No, there isn't any performance problem. It's just an unnecessary extra operation. It might take a bit longer to execute, but should be hardly noticeable. It's akin to return x+0
instead of return x
for an integer x
. Or rather, exactly equivalent to the pointless .then(x => x)
.
它不会造成实际伤害,但我认为它的风格很糟糕,表明作者没有完全理解hend promises 和 async
/await
.
It doesn't do actual harm, but I'd consider it bad style and a sign that the author does not fully comprehend promises and async
/await
.
但是,有一种情况会产生重要影响:
However, there's one case where it make an important difference:
try {
…
return await …;
} …
await
确实抛出拒绝,并且在任何情况下都等待在 catch
或 finally
处理程序执行之前的承诺解析.一个简单的 return
会忽略它.
await
does throw on rejections, and in any case awaits the promise resolution before catch
or finally
handlers are executed. A plain return
would have ignored that.
这篇关于“返回等待"是否存在性能问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!