The differences between AngularJS $applyAsync and $evalAsync

A while ago I’ve written a blog post about “The differences between AngularJS $apply, $digest, and $evalAsync“. This blog post introduced the 3 methods and execution phases of AngularJS digest cycle.
Recently in AngularJS 1.3 and above AngularJS team introduced new scope function which calls $applyAsync.

AngularJS $applyAsync and $evalAsync

Within this blog post I will explore the similarities and differentiation between $AngularJS $applyAsync and $evalAsync.

Similarities

1. Both work async.
2. Both update the global queue of expressions.
3. Both schedule timeout in case they can’t evaluate in the same digest cycle.

Differentiation

1. Flushing of the expression queue – Flushing of applyAsync only happens at the $rootScope and only happens once. If the digest cycle has already started the evaluation of the expression will only applied at the next digest cycle. Flushing of evalAsync makes sure that somewhere in the current digest cycle the expression will evaluate.
2. $applyAsync most of the time will create another timeout cycle.

Conclusion

I have read a lot of blog post and explored the AngularJS code, I still don’t 100% sure why and what is the specific use case of $applyAsync.
From the AngularJS code it seems that they are using it in the $http service.
From what I read and can understand it seems like it gives the opportunity of handling several responses in 1 digest cycle, because $applyAsync after ~10ms which this way it can collect several responses and handle them in one cycle.

Taken From the AngularJS source code:

* Configure $http service to combine processing of multiple http responses received at around
* the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
* significant performance improvement for bigger applications that make many HTTP requests

To sum it up, async expressions added by $evalAsync() will be executed in the same digest. Async expressions added by $applyAsync() will be executed at a later point in time ~10ms (Depends on the timer of the digest cycle which mostly is 10ms).

One thought on “The differences between AngularJS $applyAsync and $evalAsync

Leave a Reply

Your email address will not be published. Required fields are marked *