JS Asynchronous processing

Source: Internet
Author: User

JS processing asynchronous several ways JavaScript language execution environment is a "single thread", that is, only one task can be completed at a time. If you have multiple tasks, you must queue, complete the previous task, and then perform the latter task, and so on. The advantage of this model is that the implementation is relatively simple, the execution environment is comparatively pure; the disadvantage is that as long as a task takes a long time, the subsequent tasks must be queued, delaying the execution of the whole program. Common browsers are unresponsive (suspended animation), often because a certain piece of JavaScript code is running for a long time (such as a dead loop), causing the entire page to be stuck in this place and other tasks cannot be performed. To solve this problem, the JavaScript language divides the execution pattern of a task into two types: synchronous (synchronous) and asynchronous (asynchronous). "Synchronous mode" &NBSP; After a task waits for the previous task to end, and then executes, the execution order of the program is consistent and synchronized with the order of the tasks, and the asynchronous pattern is completely different, each task has one or more callback functions (callback), and after the previous task is finished, Instead of performing the latter task, the callback function executes, and the latter task executes at the end of the previous task, so the order of execution of the program is inconsistent and asynchronous with the order in which the task is ordered. Asynchronous mode   is very important. On the browser side, a lengthy operation should be performed asynchronously to avoid the browser losing its response, and the best example is the Ajax operation. On the server side, "asynchronous mode" is even the only mode, because the execution environment is single-threaded, and if all HTTP requests are allowed to execute synchronously, the server's performance will drop sharply and will soon lose its response.   Several methods of handling async one, the callback function (callback) callback is a function that is passed as a parameter to another function, which executes after that function is executed. (  that is, the B function is passed as a parameter to the a function, and then execution after the A function executes B) assumes there are two functions F1 and F2, which waits for the result of the former execution. F1 (); F2 (); If F1 is a time-consuming task, consider rewriting F1 to write F2 as a F1 callback.   Function F1 (callback) {SetTimeout (function () {//F1 task code callback (); }, 1000); }//Execute F1 (F2) in this way, we turn the synchronization operation into an asynchronous operation, F1 does not plug the program to run, the equivalent of first executing the main logic of the program, the time-consuming operation deferred execution. Callback functions are the most basic method of asynchronous programming, the advantages are simple, easy to understand and deploy, the disadvantage is not conducive to the reading and maintenance of code, the various partsHighly coupled (coupling), the process can be confusing and only one callback function can be specified per task. Note   Differentiate   callback functions and asynchronous   callbacks are not necessarily asynchronous. They are not directly related to themselves. Simple distinction synchronous callback and asynchronous callback synchronous callback: Instance code function A (callback) {Console.log ("I am a"); callback ();//Call this function} function B () {Console.log ("I Am B "); } A (B); asynchronous callback: Because JS is single-threaded, there are a lot of things to do (AJAX requests remote data, IO, etc.) is very time-consuming, if the single-threaded plug down will cause the program to wait too long the page loses its response, affecting the user experience. How to solve this problem, we can think so. Time-consuming we all throw to the async to do, do it again under the notice we finished, we get the data continue to go down. var xhr = new XMLHttpRequest (); Xhr.open (' POST ', url, true); The third parameter determines whether to xhr.send (data) in an asynchronous manner; Xhr.onreadystatechange = function () {if (xhr.readystate = = = 4 && Xhr.status = =) {///do Something}} above is a code that browses When an AJAX request is initiated, a single thread is opened to initiate the HTTP request, so that the time-consuming process can be run by itself, and the value of the,readystate  is changed during the request of the thread, and each change triggers a   onreadystatechange   function, to determine whether the correct to get the return result.   Event monitoring adopts event-driven mode. The execution of a task does not depend on the order of the Code, but on whether an event occurs. The listener functions are: On,bind,listen,addeventlistener,observe or F1 and F2 for example. First, bind an event (in jquery notation) for F1. F1.on (' Done ', f2); The above code means that when the F1 happens, the F2 is executed. The F1 is then rewritten: function F1 () {settimeout (function () {//f1 's Task code F1.trigger (' Done '); },1000); }f1.trigger (' Done ') indicates that the Do event is immediately triggered when execution completes, thereby starting execution of F2. The advantages of this method: it is easier to understand, can bind multiple events, each event can specify multiple callback functions, and can be decoupled to facilitate the implementation of modularity. The disadvantage of this approach is that the entire program becomes event-driven and the running process becomes unclear. Event Monitoring method: (1) OnClick method Element.onclick=function () {//Processing function} Pros: Writing compatibility to mainstream browser disadvantage: When the same element elements are bound to multiple events, Only the last event will be added for example: element.onclick=handler1; Element.onclick=handler2; Element.onclick=handler3; only Handler3 will be added to execute, so we use another method to add events (2) Attachevent and Addevenlistener methods//ie:attachevent Elment.attachevent ("onclick", handler1); Elment.attachevent ("onclick", handler2); Elment.attachevent ("onclick", Handler3); The above three method execution order: 3-2-1;//standard AddEventListener Elment.addevenlistener ("click", Handler1,false); Elment.addevenlistener ("click", Handler2,false); Elment.addevenlistener ("click", Handler3,false); Execution order: 1-2-3;ps: The third parameter of the method is the bubble fetch, which is a Boolean value: When False is expressed by the inward, true is represented by the outside. <div id= "Id1" > <div id= "id2" ></div> </div>document.getelementbyid ("Id1"). AddEventListener ( "Click", Function () {console.log (' id1 ');},false); document.getElementById ("Id2"). AddEventListener ("click", function () {console.log (' id2 ');},false); Click Id=id2 Div, first output in console, output id2, output id1 document.getElementById ("Id1"). AddEventListener ("click", Function () { Console.log (' id1 ');},false); document.getElementById ("Id2"). AddEventListener ("click", Function () {console.log (' id2 ');},true); Click Id=id2 Div, first in sonsole China output, first output id1, in the output id2  three, publish/subscribe we assume that there is a "signal center", a task is completed, to the signal Center "release" (publish) a signal, Other tasks can "subscribe" to the Signal Center (subscribe) to know when they can start executing. This is called the "Publish/Subscribe Mode" (Publish-subscribe pattern), also known as the "Observer Mode" (Observer pattern). There are several implementations of this pattern, with Ben Alman's tiny Pub/sub, which is a plugin for jquery. First, F2 subscribes to "done" signals to the signal center jquery. Jquery.subscribe ("Done", F2); Then, F1 is rewritten as follows: function F1 () {setTimeout (function () {//F1 task code jquery.publish ("Do   "); }, 1000); }jquery.publish ("done") means that after the completion of the F1 execution, the "Do" signal is released to the signal center jQuery, triggering the execution of the F2. In addition, F2 can also unsubscribe (unsubscribe) jquery.unsubscribe ("Done", F2) after completion of execution, and this method is similar in nature to "event snooping", but significantly better than the latter. Because we can monitor the operation of the program by looking at the message center to see how many signals exist, how many subscribers each signal has.   Promise Objects (Promise mode) (1) The Promise object is a specification, a pattern proposed by the COMMONJS workgroup, designed to provide a unified interface for asynchronous programming. (2)Promise is a pattern that promise can help manage the code returned in an asynchronous manner. He tells the code to encapsulate and add a management layer similar to event handling. We can use promise to register the code that will run after promise succeeds or fails. (3) When the promise is complete, the corresponding code will be executed. We can register any number of functions to run after success or failure, or register an event handler at any time. (4) There are two states of promise: 1, Wait (pending), 2, complete (settled). The promise will be waiting until the asynchronous call it wraps returns/times out/ends. (5) This time the promise state becomes complete. Completion states are divided into two categories: 1, resolution (resolved), 2, rejection (rejected). (6) Promise settlement (resolved): means a smooth end. Promise refusal (rejected) means that the end is not successful. Promise Var P=new promise (function (resolved))//is handled here. Perhaps you can use Ajax SetTimeout (function () {var result=10*5; if (result===50) {resolve (50);} Else{Reject (new Error (' Bad Math '));},1000); }); P.then (function (Result) {Console.log (' Resolve with a values of%d ', result);}); P.catch (function () {console.error (' Something went wrong ');}); (1) The key to the   of the code is the invocation of settimeout (). (2) It is important that he calls the functions resolve () and reject (). The resolve () function tells the promise user that promise has been resolved, and the Reject () function tells promise that the user promise failed to complete successfully. (3) Some other promise codes are used. Note Then and catch usages, which you can imagine as handlers for the onsucess and OnFailure events. (4) The ingenious place is that we will promise processing with state separation. That is, we can call P.then (or P.catch) many times, regardless of the state of promise. (5) Promise is the ECMAScript 6 manages the standard way of asynchronous code, and the JavaScript Library uses promise to manage Ajax, animations, and other typical asynchronous interactions. Simply put, the idea is that each asynchronous task returns an promise object that has a then method that allows you to specify a callback function. For example, F1 's callback function F2, can be written as: F1.then (F2), F1 to be rewritten as follows (using jquery implementation): function F1 () {var dfd=$.deferred (); settimeout (function () {//   F1 's Task Code dfd.resolve (); },500); return dfd.promise; The advantages of this writing: The callback function written in the chain, the process can be seen very clearly, and a set of matching methods, can achieve a lot of powerful functions.   For example, specify multiple callback functions F1 () then (F2) and then (F3); For example, specify the callback function when the error occurred: F1 (). Then (F2). Fail (F3); It has the benefit of one of the previous three methods: if a task is completed and a callback function is added, the callback function executes immediately. So you don't have to worry about missing an event or a signal. The disadvantage of this approach: writing and understanding are relatively difficult.

JS Asynchronous processing

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.