Sean Paulson wrote:my question is how does it know to return the wakeup function as a new promise and not the log function? (or both?)
I am amusing [sic] it is returning the wakeup function as a promise object to be precise(also keeping it in a unresolved state until the wakeup is called).
await wakeable(); // returns to event loop here
It doesn't return either function. The call to create the promise returns a Promise instance.
Sean Paulson wrote:
My confusion is with the wakeup() how is wakeup set to the resolve function?
Bear Bibeault wrote:
Sean Paulson wrote:
My confusion is with the wakeup() how is wakeup set to the resolve function?
It isn't. It's set to the anonymous function, which in turn calls the resolve function.
Bear Bibeault wrote:It isn't. It's set to the anonymous function, which in turn calls the resolve function.
Sean Paulson wrote:
really? in his code comments it states
Paul Clapham wrote:If this were real life, I would strongly suspect that the comment was written when the code was wakeup = resolve, and then logging was added to the code as shown but the comment wasn't changed.
Stephan van Hulst wrote:What makes you think that the resolve function that is called inside the wakeup function would lose its link to the Promise that created it? If you call wakeup outside of the executor that you pass to the Promise constructor, what promise would there be to resolve other than the one that you created the wakeup function inside of?
Sean Paulson wrote:so wakeup is passed to the promise constructor?
Sean Paulson wrote:so wakeup is passed to the promise constructor?
Paul Clapham wrote:But this isn't Java. So there's some mechanism which makes the value of "makeup" belong to the newly-created instance of Promise rather than belonging to some external code.
Stephan van Hulst wrote:
Sean Paulson wrote:so wakeup is passed to the promise constructor?
No. wakeup is just a variable that all the code that you have posted can access. When you create a new Promise, the Promise constructor runs the executor function that you pass to it. That executor function assigns a new function object to the wakeup variable. This function object has a reference to the resolve function that is part of the Promise instance that you just created. If you create a second Promise, wakeup will be reassigned a new function object that now references the resolve function of the second Promise instance.
Sean Paulson wrote:That makes sense...this code seems like it would be reckless to use though.