jQuery 中的 Deferred() 、 Angular 中的 $q() 、ES6 中的 Promise 都是为了解决异步而各自实现或定义的方法。
$.Deferred() 可以返回一个新的 deferred 对象。
$.Deferred() 返回（A function that is called just before the constructor returns）。
The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (
But not ones that change the state (
rejectWith , and
target is provided,
deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.
If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via
deferred.promise() so other code can register callbacks or inspect the current state.
$q can be used in two fashions — one which is more similar to Kris Kowal’s Q or jQuery’s Deferred implementations, and the other which resembles ES6 (ES2015) promises to some degree.
Note: progress/notify callbacks are not currently supported via the ES6-style interface.
Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
Differences between Kris Kowal’s Q and $q
Here are two main differences:
- $q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.
- Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains all the important functionality needed for common async tasks.