Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

javascript - Does awaiting a non-Promise have any detectable effect?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...