First, preface
In order for the front end to return to heaven from the callback of the underworld, jQuery
also introduced Promise
the concept. Promise
is a more elegant abstraction of the code's asynchronous behavior, and with it, we can write asynchronous code just like we write synchronous code. jQuery
started with version 1.5. CommonJS
The PROMISE/A specification is a heavyweight scheme, but not strictly implemented according to specifications, there are some API differences.
OK, let's take a look at their features ( This example is based on the jquery 1.8 version above ).
Ii. examples
When we used to write animations, we usually do this:
$('. Animateele '). Animate ({ opacity:4000, function () { $ ( width: ' 100px ' },2000,function () { //it hurts so much. $ ( '. AnimateEle3 '). Animate ({ Height: ' 0 ' },2000);
If you use callbacks like this, it hurts. Fortunately, there are some ready-made Promise
solutions to gracefully solve this problem.
Let's look at jQuery
the solutions provided.
var animate1 = function () { Return$(opacity:4000). Promise ();}; var animate2 = function () { return $ ( AnimateEle2 '). Animate ({width:2000). Promise ();}; var animate3 = function () { return $ (height: ' 0 '}, ). Promise ();}; //so easy, with wood, so clear, there are $. When (Animate1 ()). then (animate2). then (animate3);
Obviously, the changed code is easier to read.
However, the above code, some of the details of the things are not disclosed, accidentally, it is easy to make mistakes, do not get the order we want to complete the effect of animation. Let's take a full jQuery
promise
look at the provided and deferred
object methods to see how we can use them.
Iii. Promise and Deffered object methods
promise
An object is actually deferred
a special case of an object, because an object promise
cannot change the asynchronous state, and the object deferred
can. This is clearly reflected in their approach design.
1.promise Object Methods
In general, we can use methods for DOM, animation, and Ajax-related methods promise
. Invokes a promise
method that returns an promise
object. You can call methods in a chain promise
.
There are three common methods for Promise objects : done
, fail
, then
.
Other methods do not remember, jquery
there are too many interface methods, in my opinion is very verbose, and early event method binding,,, and live
delegate
bind
ultimately not all belong to on
the tube.
The code example is as follows:
1.DOM How to use promise
:
var box=$(‘#box‘);box.promise().done(function(ele){ console.log(ele);//jQuery box});
2.Ajax Use promise
method (the default is to return an promise
object, so you do not have to explicitly call the promise
method):
$.post(‘/‘,{}).done(function(data){ console.log(‘请求成功‘);}).fail(function(){ console.log(‘请求错误‘);});
Animation samples are already available and are not listed repeatedly.
2.deferred Object Methods
For objects, that is, the deferred
use of $.Deferred()
methods, and $.when()
other methods created by the object, like the following common methods:
resolve
, reject
, notify
;
done
, fail
, progress
;
There are also promise
, then
and always
methods.
The reason for this is that they correspond, that is, the callback that the method triggers, the callback that will trigger resolve
done
reject
fail
, and notify
the callback that will trigger progress
.
Look directly at the code:
var wait = function (ms) { var DTD = $. Deferred (); SetTimeout (Dtd.resolve, MS); //setTimeout (Dtd.reject, MS); //setTimeout (dtd.notify, MS); return dtd.promise (); //here you can also return directly to Dtd};wait (2500). Done (function () { Span class= "indent" > Console.log ( ' haha, teacher too, you can keep Swaiiow waiting ');}). Fail (function () { Console.log (function (res) { Console.log (
We see that the above code, in the wait
function, returns an promise
object, not an deferred
object.
To know that the promise
object is not, and so on, resolve
means that reject
notify
you cannot promise
make state changes to the object, only in done
or in the fail
callback configuration. So, if you do this, you will wait(2500).resolve()
get an error, because wait(2500)
the promise
object is returned and there is no resolve
method.
However, to do so, there is a benefit, we put dtd
this deferred
object in the wai
t function, as a local variable, to avoid the global pollution, further through the promise
method, dtd
the deferred
object is converted to promise
avoid the function wait
External possible state changes (if we do have this requirement).
Like what:
var wait = function(ms) { var dtd = $.Deferred(); setTimeout(dtd.resolve, ms); // setTimeout(dtd.reject, ms); // setTimeout(dtd.notify, ms); return dtd; //此处也可以直接返回dtd};wait(2500).reject().fail(function(){ console.log(‘失败了...............‘);});
We changed the state of the wait
returned deferred
object externally, which would necessarily trigger the object's fail
callback function.
For a always
method, it is easy to understand the literal meaning that the deferred
object, either or both resolve
reject
, triggers the callback for the method.
3. Other commonalities
Here then
$.when
is the talk and the use of the method. They promise
also apply to objects.
-
$.when
method accepts multiple deferred
object, or plain JavaScript object, returns promise
object.
-
then
method accepts three callbacks, respectively deferred
Object resolve
, reject
,notify
post-Trigger callback, returning a promise
object. Note that the function must be passed in, and the function only returns a promise
object to allow asynchronous events to execute in the expected order.
Let's take a look at the very beginning of the animated example code, $.when(animate1()).then(animate2).then(animate3)
the $.when
method accepts a animate1
function execution result, that is, to get an object, and then promise
then
just accept a variable name, so that the result is an anonymous function body, The object is returned in the function promise
. Just in line with our then
request for acceptance parameters.
If we change the execution to: $.when(animate1()).then(animate2()).then(animate3())
, this result is three animation synchronous execution. With the same $.when(animate1(),animate2(),animate3())
.
Since then
it is so demanding, it is similar to the method, and the same is true then
done
fail
progress
.
Reference: http://segmentfault.com/a/1190000000523676
The Promise object is actually a special case of the deferred object.