user445670 user445670 - 4 months ago 15
Javascript Question

What is the execution sequence of javascript async?

Consider the following angular code

// 1.
var something = 0;
// 2.
something = 1;

.then(function() {
// 3.
something = 2;

// 4.
something = 3

// 5.
something = 4

// 6.

Say that after statement
, the

Does statement
get to execute next or does statement
get to execute next?

If statement
get to execute next does it mean that it will continue to execute subsequent statements until the thread is not in used?

If statement
get to execute next does it mean that the thread always get interrupted by the promise resolving using the time of the call order?

What is the general rule of ordering, and are there exceptions for other more complex situation, like nested promise etc?


While javascript uses an asynchronous event loop, javascript code execution is serial, and completely deterministic. Your code will execute in this order:

  1. something = 0
  2. something = 1
  3. $http.get('some_url')
  4. something = 3
  5. something = 4
  6. $http.get('some_url')

After step 6 is where the execution can diverge. The code will wait until one of the http requests has completed, then resolve the promise for that request, which subsequently runs the function in your then statement. (2 requests cannot resolve at the same time since javascript executes in serial, as previously stated)

To answer your question directly, code execution cannot be interrupted in javascript. When a function is executed, it runs until it returns. Any asynchronous operations that complete during that time will only be able to run after the function returns. Multiple possible events like the one above are executed in "first in first out" order of when they are triggered.