The Event loop

In order to answer such a question we need to understand the order of execution of asynchronous operations. This is pretty straightforward in a synchronous world. Everything is executed serially and line by line. When an operation is ready, the next operation takes place and executes itself until we have no more code to execute.

This is not possible with async operations though, because of their nature passing the torch to the next function, and because most of the times we don't know exactly how much time the operation will take to finish. To be honest, this 'problem' is the biggest benefit of those operations. How do we know then? 

Well the answer is simple. Any time we define an async function, the browser (or the server, depending on what kind of script we write) performs this operation (let's say send data to server from a client), but in the meantime 'passes the torch' to the next executable piece of code, the next line! Thus the rest of your code executes itself normally as we know. 

When the response from the server comes back, the browser gets back to the asynchronous function definition and executes the function that has to be done. This is happening after all the rest of our code has already finished! 

That's good. But what happens in case there is still code being executed and the response from the server comes back? What is the order of precedence in this case? The event loop is clear again. All the asynchronous operations that are on 'pending state' will be  executed last and after the whole code stack is cleared. That means even if the response has come back from the server, in order to do something with it, we need to wait until the browser has no other task to do at the time.

Highly recommended: If you want to know exactly how the event loop works: Watch here: