gpt4 book ai didi

javascript - 等待非 Promise 是否有任何可检测的效果?

转载 作者:行者123 更新时间:2023-12-04 05:22:26 24 4
gpt4 key购买 nike

一 jar await一个非 Promise 和 that's good so .

所有这些表达式都是有效的并且不会导致错误:

await 5
await 'A'
await {}
await null
await undefined

有没有 可检测效果等待一个非 promise ?为了避免潜在的错误,人们应该注意哪些行为差异?任何性能差异?

以下两行是完全相同还是理论上不同?:
var x = 5
var x = await 5

如何?有什么例子可以证明差异吗?

PS:根据 TypeScript authors , 它们是有区别的:

var x = await 5; is not the same as var x = 5;; var x = await 5; will assign x 5 in the next tern, where as var x = 5; will evaluate immediately.

最佳答案

await不是无操作。如果等待的东西不是一个 promise ,它被包裹在一个 promise 中,那个 promise 是等待的。因此await改变执行顺序(但你不应该依赖它):

console.log(1);
(async function() {
var x = await 5; // remove await to see 1,3,2
console.log(3);
})();
console.log(2);

另外 await不仅适用于 instanceof Promise s 但在每个带有 .then 的对象上方法:
await { then(cb) { /* nowhere */ } };
console.log("will never happen");

Is there any detectable effect of awaiting a non-Promise?



当然, .then如果它存在于等待的事物上,则被调用。

Is there any difference in behavior one should be aware of to avoid a potential error?



如果您不希望它成为 Promise,请不要将方法命名为“then”。

Any performance differences?



当然,如果您等待某些事情,您将始终将继续推迟到微任务。但一如既往:你可能不会注意到它(作为一个观察结果的人)。

关于javascript - 等待非 Promise 是否有任何可检测的效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55262996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com