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 initialized
setTimeout()
is executed, its callback will be called in the next tick
go()
is declared
go()
is executed
await
is triggered inside go()
, which executes obj.then()
, assigning the resolving function to obj.func
- it has not been resolved yet so the tick ends here
Second tick
setTimeout()
callback is executed, resolving the promise through obj.func()
with the value 57
Third tick
- the control is back to
go()
, and the result 57
is logged