等待一个非承诺有任何可察觉的影响吗?

一个人可以 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;将在下一个结构中赋值 x5,其中 var x = 5;将立即求值。

20899 次浏览

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).

Completely agreed with Jonas's statements. One thing that was not answered in his question was Are the following two lines completely same or do they theoretically differ?:

following two lines are not completely same, they're theoretically different.

  1. var x = 5
  2. var x = await 5

execution time in my console for 1st and 2nd statement is 0.008056640625ms and 0.055908203125ms respectively. async/await, setTimeOut etc are APIs provided by Run time in which JavaScript Run time is running. Putting await on a non-promise will be executed in event-loop. Line 1 will be executed right after reaching the stack but the line 2 will take few time(milliseconds) as it will 1st go to the stack and then to the task queue after skipping webAPI waiting section because there's no promise to be resolved & finally after that control will be given to stack again for execution.