Using the $. Deferred object in jQuery as an example to explain how the promise object handles asynchronization _ jquery

Source: Internet
Author: User
Promises is a kind of abstraction that makes code asynchronous behavior more elegant. it is likely to be the next programming paradigm of JavaScript. a Promise represents the task result, regardless of whether the task is completed or not. This document uses jQuery $. the Deferred object is used as an example to explain how the promise object handles the asynchronous problem. if you need a friend, Promises is a kind of abstraction that makes code asynchronous behavior more elegant. it is likely to be the next programming paradigm of JavaScript, A Promise indicates the task result, whether or not the task is completed.

Some modern browsers have provided native Promise objects, which follow the Promise/A + standard. In jQuery1.5 +, $. Deferred is provided (which can be converted to a promise object ). Many well-known frameworks also provide promise objects. The promise object is already a very important pattern in javascript. it shows elegance in solving the asynchronous problem, which is exactly what javascript needs. The following uses the $. Deferred object in jQuery as an example to illustrate how the promise object handles the asynchronous problem. For more information about the $. Deferred object, visit the jQuery official website.

1. encapsulate asynchronous operations

First, let's take loading images as an example and look at the following code:

// Load the Image function var loadImg = function (url) {var img = new Image (), deferred = $. deferred (); img. src = url; img. onload = function () {// if the call succeeds, deferred is triggered. resolve deferred. resolve (this) ;}; img. onerror = function (e) {// deferred is triggered when a failure occurs. reject deferred. reject (e) ;}; // return promise object return deferred. promise () ;}; // request Image var request = loadImg ('http: // r2.ykimg.com/051510954affc2d6737b343930afad6'); // request successful request. done (function (img) {// code}); // You can register multiple callbacks. when the request is successful, it is executed in the registration order, fail and always also have this type of request. done (function (img) {// code}); // request failed. fail (function () {// code}); // request completed. always (function () {// code });

The above code encapsulates the image loading operations, delegates them to $. Deferred, and finally generates a promise return. This method is more clean and clearer than the method of externally exposed callback. Another more important reason for doing so is the promise connection.

2. promise connection

Let's take the above image loading code as an example. let's take a look at how to connect promise and see the following code:

Var request = loadImg ('http: // b1.hucdn.com/upload/item/1411/13/89613257775992_800x800.jpg'); request. done (function (img) {// code}); // request returns promisevar request3 = request after connecting to another promise. then (function (img) {// connection request1 var request1 = loadImg ('http: // callback); return request1 ;}, function (e) when request execution is successful) {// connection request2 var request2 = loadImg ('http: // b1.hucdn.com/upload/item/1410/19/29379357%25_800x800.jpg'); return request2 ;}); // when the request is executed and request1 or request2 is successfully executed, request3.done (function (done) {// code });

The promise object provides the then method. it accepts two callbacks: onResolve and onReject, and returns promise in the callback to complete the connection between promise. In this way, asynchronous operations can be executed in serial mode.

At the same time, jQuery also provides another connection method, depending on the code:

Var request = loadImg ('http: // b1.hucdn.com/upload/item/1412/23/481888271393820.800x800.jpg'); var request1 = loadImg ('http: // callback); // pass $. when connection promisevar request2 =$. when (request, request1); request2.done (function (img, img) {// code });

JQuery provides the $. when function, which accepts n promise objects as parameters and connects the execution results of promise. In this way, multiple asynchronous operations can be executed in parallel.

III. The End

The code here is to load images as an example. The same method can be applied to other asynchronous operations. For example, $. ajax and $. fn. animate in jQuery, the promise is returned when they are called. On the node side, you can also encapsulate some asynchronous operations (read databases, read files, etc.) into promise. Then, merge multiple promise operations so that they can be executed in serial or parallel.

Appendix: deferred object

In addition to converting promise objects, deferred is also a useful object. In addition to the methods and attributes of objects like promise, it also provides the notify function and progress function. These two functions are of great use when implementing the progress bar and waterfall stream.

When the progress bar is implemented, the resolve and done functions can be used to define the trigger time and trigger logic when the progress bar reads 100%, notify and progress functions can be used to define the trigger time and trigger logic of the progress bar in reading. The reject and fail functions can be used to define the trigger time and trigger logic when the read progress fails.

When implementing a waterfall stream, the resolve and done functions can be used to define the trigger time and trigger logic when all the data has been loaded to the page, notify and progress functions can be used to define the trigger time and trigger logic for the waterfall stream to read the next page.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.