Skip to content
Advertisement

Losing object reference in Javascript with await

I was learning the event loop of Js and tried to run this function:

JavaScript

On running this code gave output as follows:

JavaScript

I am not able to understand why did a lose its value (the object assignment). I have searched for this behavior but was not able to understand from the answers. Can someone please explain what is the order of execution which results in this output.

Advertisement

Answer

When you await the newly created promise, you’re not assigning the promise to a, you’re assigning the resolve value of it.

JavaScript

If you want to keep the await while also retrieving the reference, you can separate those two steps:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement