等待未承诺会产生任何可察觉的影响吗? [英] Does awaiting a non-Promise have any detectable effect?

查看:56
本文介绍了等待未承诺会产生任何可察觉的影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个人可以await一个非承诺书,并且很好. >

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

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

等待无承诺有可检测的效果吗?为了避免潜在的错误,应该注意哪些行为上的差异?有任何性能差异吗?

以下两行是完全相同的,还是在理论上是不同的?

var x = 5
var x = await 5

如何?有什么例子可以证明两者之间的区别吗?

PS:根据 TypeScript作者,存在区别:

var x = await 5;var x = 5;不同; var x = await 5;将在下一个tern中分配x 5,因为var x = 5;将立即求值.

解决方案

await不是禁止操作.如果等待的事物不是承诺,则将其包装在承诺中,等待该承诺.因此,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,而且适用于使用.then方法的每个对象:

await { then(cb) { /* nowhere */ } };
console.log("will never happen");

等待不承诺有没有可检测的影响?

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

为了避免潜在的错误,应该注意哪些行为上的差异?

如果您不希望将其命名为Promise,请不要将其命名为"then".

是否有任何性能差异?

当然,如果您等待某些事情,则始终会将延续推迟到微任务上.但还是一如既往:(作为观察结果的人类,您可能不会注意到它.)

One can await a non-Promise and that's good so.

All these expressions are valid and cause no error:

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

Is there any detectable effect of awaiting a non-Promise? Is there any difference in behavior one should be aware of to avoid a potential error? Any performance differences?

Are the following two lines completely same or do they theoretically differ?:

var x = 5
var x = await 5

How? Any example to demonstrate the difference?

PS: According TypeScript authors, there is a difference:

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 is not a no-op. If the awaited thing is not a promise, it is wrapped in a promise, that promise is awaited. Therefore await changes the execution order (but you should not rely on it nevertheless):

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

Additionally await does not only work on instanceof Promises but on every object with a .then method:

await { then(cb) { /* nowhere */ } };
console.log("will never happen");

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

Sure, .then gets called if it exists on the awaited thing.

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

Don't name a method "then" if you don't want it to be a Promise.

Any performance differences?

Sure, if you await things you will always defer the continuation to a microtask. But as always: You won't probably notice it (as a human observing the outcome).

这篇关于等待未承诺会产生任何可察觉的影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆