Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does await await promise-like objects? [duplicate]

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

like image 344
wezten Avatar asked Jul 18 '17 11:07

wezten


People also ask

Is await the same as promise?

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.

What happens when you await a promise?

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.

What happens if you await a promise twice?

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.

Which is faster async await or promise?

Yes, you read that right. The V8 team made improvements that make async/await functions run faster than traditional promises in the JavaScript engine.


1 Answers

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

  1. obj is initialized
  2. setTimeout() is executed, its callback will be called in the next tick
  3. go() is declared
  4. go() is executed
  5. await is triggered inside go(), which executes obj.then(), assigning the resolving function to obj.func
  6. it has not been resolved yet so the tick ends here

Second tick

  1. setTimeout() callback is executed, resolving the promise through obj.func() with the value 57

Third tick

  1. the control is back to go(), and the result 57 is logged
like image 153
Antonio Val Avatar answered Oct 05 '22 23:10

Antonio Val