api:http://www.css88.com/jqapi-1.9/category/deferred-object/
Processing of asynchronous programming
The JavaScript execution process is divided into "synchronous" and "asynchronous"
The traditional asynchronous operation returns the result using the callback function after the operation is complete, and the callback function contains the subsequent work. This is also the main cause of the difficulty of asynchronous programming:
We have been accustomed to writing code logic "linearly", but the callback functions brought by a large number of asynchronous operations will break down our algorithm.
Nested callbacks
Animation For example, the next animation to wait until the last execution can continue, the process will be written in the callback
Perform multiple animations (' Ele1 '). Animate ({opacity: '. 5 '}, 4000, function () {$ (' ele2 '). Animate ({width: ' 100px '}, 2000, Function () {$ (' ele3 '). Animate ({height: ' 0 '}, 2000); });});
The Code programming logic above is also correct, but for such asynchronous nested callback logic, the more nested we are, the more deeply the code structure level becomes. First of all, reading will become difficult, followed by strong coupling, the interface becomes bad expansion. We need a pattern to solve this problem, and that's what promises is going to do.
In order for the front end to return to heaven from the callback of Hell, JQuery also introduced the concept of Promise. Promise is an abstraction that makes the code asynchronous behave more gracefully, and with it, we can write asynchronous code just like we would write synchronous code. This stuff looks complicated, actually we just have to grab the core and use it.
Observe the code on the right:
Through $. Deferred processed code, it is clear that the callback is not nested, although the code seems a bit more, but in fact, each code execution part is encapsulated, only left the interface processing deferred, is the execution of the process control to the deferred , the advantage is that when we write nested functions, we can write synchronization code with the pipe style provided by deferred.
Dtd.then (function () { ///Action 1}). Then (function () { //Operation 2}). Then (function () {//Operation 3})
Here are 3 steps to understand
var DTD = $. Deferred (); Create Dtd.resolve (); Success Dtd.then () //Execute callback
jquery Lingering objects