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.
If you want to add a callback to the function, you usually do this.
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.
The code is as follows:
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.
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.