4 ms·
I am highly confused as to what you might have thought other than that the callback itself could block... would you mind sharing? (I am an educator and teach a
by saurik 9y ago
I am highly confused as to what you might have thought other than that the callback itself could block... would you mind sharing? (I am an educator and teach a class on programming languages, so my question here is one of some serious interest: to understand the beginner's mindset better.)
- baron816 9y agoI just had a hard time building a mental model of what the asyc function was doing, and the analogy I had heard before made it sound more like a multi-threaded process (something I also didn't fully grasp). The analogy I had heard was that of a check-in window at a doctors office: the nurse would give you a form to fill out and when you were done, you could get back in line and hand the form back to the receptionist. I think the analogy was trying to show that there weren't multiple windows to check in at, nor did you have to stand at the window while you're filling out the form, preventing people behind you from getting the form. But the reason it's a bad analogy, and why I was confused, was that it made it appear that you (the patient) are the callback function, and you're doing some processor intensive work when you sit down to fill out the form. It would have been clearer had the analogy specified that you are actually a backend server/web-worker, but even that doesn't fit right. So, I think it would be best to avoid using analogies. The event loop isn't that complicated: async functions just sit around waiting for a response, and they stick their callback on the event queue when they get that response. When the call the stack is cleared (from it's synchronous functions), the first callback in the event queue moves to the call stack (ie, it gets called), and that process repeats until the queue is cleared.
- fla 9y agoI can understand the confusion. I think the construct with an inline function that executes something "later but synchronously" is quiet special and very specific to the event loop pattern. If I try to forget all I know about JS, I can think of two different _wrong_ ways to interpret this code: a) executes the callback immediately in-line, as it was synchronous b) executes the callback at a later time, in a different thread.