Home > Web Front-end > JS Tutorial > Promise mode encapsulation example of JavaScript asynchronous callback_javascript skills

Promise mode encapsulation example of JavaScript asynchronous callback_javascript skills

WBOY
Release: 2016-05-16 16:45:40
Original
1268 people have browsed it

Interactions on web pages are becoming more and more complex, and JavaScript has more and more asynchronous operations. For example, common ajax requests require a response operation when the request is completed. The request is usually asynchronous. During the request process, the user can also perform other operations without blocking the page. This asynchronous interaction effect is good for the user. Quite friendly. But for developers, it is very unfriendly to handle this kind of operation in large quantities. The operation completed by the asynchronous request must be pre-defined in the callback function, and this function must be called when the request is completed. This non-linear asynchronous programming method will make developers very uncomfortable, and it also brings a lot of inconvenience, increases the coupling and complexity of the code, and the organization of the code will also be very inelegant, greatly reducing the efficiency of the code. Maintainability. The situation is more complicated. If an operation has to wait until multiple asynchronous ajax requests are completed before it can be carried out, there will be nesting of callback functions. If you need to nest several levels, then you can only ask for blessings.
Let’s take a look at the following common asynchronous function.

Copy code The code is as follows:

var showMsg = function(){
setTimeout( function(){
alert( 'hello' );
}, 5000 );
};

If you want to add a callback to the function, you usually do this.

Copy code The code is as follows:

var showMsg = function( callback ){
setTimeout (function(){
alert( 'hello' );
// Add callback here
callback();
}, 5000 );
};

If you use Promise of easy.js, the method of adding callbacks will be much more elegant, provided that the original function needs to be encapsulated into a promise instance.

Copy code The code is as follows:

var showMsg = function(){
// Construct a promise instance
var promise = new E.Promise();

setTimeout(function(){
alert( 'hello' );

// Change the state of promise
                                                                                                                                          who’ who who’ who’ who who’ who who’ who who’ who who’ who who who who’s who who who who’s who who’s who who’s who who’s who who’s who who’s who who’s to to, being 50000000000 >
There are three key steps to encapsulate an ordinary function into a promise instance. The first step is to construct a promise instance inside the function. The second step is to change the status of the promise to completed after the deployment function is executed. The third step is to return this promise instance. Each promise instance has three states, namely pending (not completed), resolved (completed, successful), and rejected (rejected, failed). Let's take a look at how to add callbacks.




Copy code

The code is as follows:

This completely separates the callback function from the original asynchronous function. From the code organization point of view, it is much more elegant. resolve accepts a parameter that can easily be used to pass data to the callback added using the then method.
For ajax requests, easy.js directly encapsulates the ajax method into a promise object, and you can directly add the then method to call back.



Copy code


The code is as follows:

E.ajax({ url : 'test1 .php', type : 'GET'}).then(function(){ // Add a callback for successful request
}, function(){
/ / Add callback for request failure
});

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

Copy code The 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 is to store multiple promise instances into an array, and wait until all promise instances in the array are completed before executing the completed callback. Once one instance is rejected, execute it immediately. Rejected callback.

Promise pattern is one of the specifications of CommonJS. Many mainstream JavaScript libraries have corresponding implementations, such as jQuery and Dojo, which have Deferred to implement these functions. Here I still want to complain about jQuery's Deferred. Regardless of its internal use, this module should be the module with the lowest usage rate by users. This has a certain relationship with its more complicated usage.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template