Example of Promise mode encapsulation for JavaScript asynchronous callback

Source: Internet
Author: User

Web page interaction becomes more and more complex, and JavaScript asynchronous operations become more and more complex. For example, a common ajax request needs to respond to the operation when the request is complete. The request is usually asynchronous and other operations can be performed by the user during the request process without page blocking, this Asynchronous interaction effect is quite helpful to users. However, it is unfriendly for developers to deal with such operations in large quantities. The Operations completed by asynchronous requests must be pre-defined in the callback function. This function must be called when the request is complete. This non-linear asynchronous programming method will make developers very uncomfortable, but also bring a lot of inconvenience, increase the coupling and complexity of the code, and the code organization will be very not elegant, this greatly reduces the maintainability of the Code. The situation is more complex. If an operation can only be performed after multiple asynchronous ajax requests are completed, the callback function is nested. If several layers need to be nested, then you have to be blessed.
Let's take a look at this common asynchronous function.

Copy codeThe Code is as follows:
Var showMsg = function (){
SetTimeout (function (){
Alert ('hello ');
},5000 );
};

This is usually the case if you want to add a callback to the function.
Copy codeThe Code is as follows:
Var showMsg = function (callback ){
SetTimeout (function (){
Alert ('hello ');
// Add a callback here
Callback ();
},5000 );
};

If you use Promise of easy. js, the method of adding callback will be much more elegant, provided that the original function needs to be encapsulated into a promise instance.
Copy codeThe Code is as follows:
Var showMsg = function (){
// Construct a promise instance
Var promise = new E. Promise ();

SetTimeout (function (){
Alert ('hello ');

// Change the promise status
Promise. resolve ('done ');
},5000 );

// Return the promise instance
Return promise;
};

Encapsulate a common function into a promise instance. There are three key steps. The first step is to construct a promise instance within the function, the second step is to change the promise status to completed after the deployment function is executed, and the third step is to return the promise instance. Each promise instance has three statuses: pending (incomplete), resolved (completed, successful), and rejected (rejected, failed ). Next let's take a look at how to add a callback.

Copy codeThe Code is as follows:
ShowMsg (). then (function (str ){
// The callback is added here.
Callback (str );
});

In this way, the callback function is completely separated from the original asynchronous function, and the code structure is much more elegant. Resolve accepts a parameter, which can easily transfer data to the callback added using the then method.
For ajax requests, easy. js directly encapsulates the ajax method into a promise object. You can directly add the then method to call back and forth.
Copy codeThe Code is as follows:
E. ajax ({
Url: 'test1. php ',
Type: 'get'
})
. Then (function (){
// Callback for successful request Addition
}, Function (){
// Add callback for failed requests
});

The then method accepts two functions as parameters. The first function is a completed callback, and the second is a failed callback.
What if there are multiple ajax requests mentioned above? Then we need to use the when method. This method can take multiple promise instances as parameters.

Copy codeThe Code is as follows:
Var requests = E. when (E. ajax ({
Url: 'test1. php ',
Type: 'get'
}), E. ajax ({
Url: 'test2. php ',
Type: 'get'
}));

Requests. then (function (arg1, arg2 ){
Console. log ('success: '+ arg1 [0] + arg2 [0]);
}, Function (arg1, arg2 ){
Console. log ('failure: '+ arg1 + arg2 );
});

The when method saves multiple promise instances to an array and executes the completed callback only when all promise instances in the array are in the completed status, once an instance is rejected, the rejected callback is executed immediately.

The Promise mode is one of the CommonJS specifications. Many mainstream JavaScript libraries have corresponding implementations, such as jQuery and Dojo, all have Deferred to implement these functions. Here we still need to talk about jQuery's Deferred, Which is used internally. This should be a module with the lowest user usage, which has a certain relationship with its complicated usage.

Related Article

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.