jQuery Deferred、Angular $q、ES6 Promise
jQuery 中的 Deferred() 、 Angular 中的 $q() 、ES6 中的 Promise 都是为了解决异步而各自实现或定义的方法。
jQuery Deferred()
直接通过调用 $.Deferred()
可以返回一个新的 deferred 对象。
调用 $.Deferred()
时是可以传入一个函数,这个函数会先于 $.Deferred()
返回(A function that is called just before the constructor returns)。
Deferred.promise()
The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state ( then
, done
, fail
, always
, pipe
, progress
, state
and promise
).
But not ones that change the state (resolve
, reject
, notify
, resolveWith
, rejectWith
, and notifyWith
).
If 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.
Angular $q
$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.
ES6-style
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.
jQuery’s Deferred
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.