According to Mozilla, await only awaits Promises:
[rv] Returns the resolved value of the promise, or the value itself if it's not a Promise.
If you await a non-Promise, a resolved promise will be immediately returned, and it will not await. However, the following code awaits without using Promises in Chrome & FF.
var obj = {
then:func => obj.func=func
};
setTimeout(() => obj.func(57), 1000);
async function go() {
var res = await obj;
console.log(res); //shows '57' after 1000ms
}
go();
According to the specs, should await await promise-like objects that are not Promises? (I tried looking at the specs (linked from the Mozilla article), but I couldn't understand it.)
1. Promise is an object representing intermediate state of operation which is guaranteed to complete its execution at some point in future. Async/Await is a syntactic sugar for promises, a wrapper making the code execute more synchronously. 2.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
The second await is no different. It creates a microtask to “give me the promise result and run the code ahead”, and waits to be scheduled by JavaScript.
Yes, you read that right. The V8 team made improvements that make async/await functions run faster than traditional promises in the JavaScript engine.
await
is going to trigger obj.then()
, and that's causing that behavior. Because even if obj
is not a Promise, is a thenable object.
You have some information about that here.
In your case it works because:
First tick
obj
is initializedsetTimeout()
is executed, its callback will be called in the next tickgo()
is declaredgo()
is executedawait
is triggered inside go()
, which executes obj.then()
, assigning the resolving function to obj.func
Second tick
setTimeout()
callback is executed, resolving the promise through obj.func()
with the value 57
Third tick
go()
, and the result 57
is loggedIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With