Angular promises are misleading as they are not always called asynchronously

I recently debugged some promises related stuff in angular.js and noticed that angular is putting promises permissions in its evalAsync loop as shown in this diagram . My impression is that callback promises are always executed asynchronously (like a new event in the event queue). However, when using the angular engine, it is possible that if any of the promises are resolved during the digest cycle, and angular starts another iteration in the digest, then the callback for the promise is called on the same execution stack, since the evalAsync

queue is always checked first:

do { // "while dirty" loop
  dirty = false;
  current = target;

  while (asyncQueue.length) {
    try {
      asyncTask = asyncQueue.shift();
      asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
    } catch (e) {
      $exceptionHandler(e);
    }
    lastDirtyWatch = null;
  }

  traverseScopesLoop:
  do { // "traverse the scopes" loop
  ...
  } while ((current = next));
...  
} while (dirty || asyncQueue.length);

      

Not misleading?

+3


source to share


1 answer


Not sure if I would call this deceiving or not. Fact:

  • Promise callbacks are always executed asynchronously. They never call in front of .then()

    which they responded.
    To a large extent, they are never even called from user code - there is "only platform code" on the stack, as provided by the Promises / A + spec .
  • Each asynchronous callback is not guaranteed to execute its own event loop queue. There is no requirement that two callbacks should not share the same event loop. After all, they still cannot distinguish.


In your case, Angular qualifies as platform code that uses its own "event loop" - the digest loop.

+3


source







All Articles