Monday, May 20, 2024
143
rated 0 times [  149] [ 6]  / answers: 1 / hits: 24389  / 5 Years ago, wed, march 20, 2019, 12:00:00

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.



More From » ecmascript-2017

 Answers
16

await is not a no-op. If the awaited thing is not a promise, it is wrapped in a promise and that promise is awaited. Therefore await changes the execution order (but you should not rely on it nevertheless):


The following outputs 1, 2, 3:




console.log(1);

(async function() {
var x = await 5;
console.log(3);
})();

console.log(2);




With the await removed it's 1, 3, 2:




    console.log(1);

(async function() {
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).


[#52395] Thursday, March 14, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janjadonb

Total Points: 4
Total Questions: 114
Total Answers: 118

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
janjadonb questions
;