Front-End Basics (iv): JS asynchronous mode: 1, callback function, 2, event Listener, 3, observer mode, 4, Promise Object

Source: Internet
Author: User
Tags event listener

The JavaScript language divides the execution pattern of a task into two types: synchronous (synchronous) and asynchronous (asychronous).

"Synchronous Mode" is the completion of a task, followed by a task followed by execution, the execution order and order of the program is always, the "Asynchronous Pattern" is completely different, each task has one or more callback functions (callback), the end of the previous task is not to perform the next task, 20 executes the callback function, and the latter task is executed at the end of the previous task, so the execution order of the program is inconsistent with the order of the task, asynchronously.

in the browser side , the time-consuming operation should be executed asynchronously, avoiding the number of browsers to respond, 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 drops sharply and soon loses its response.

There are 4 methods in the "asynchronous Mode", these 4 methods can write more reasonable structure, better performance, maintenance more convenient JS code. These four modes are:

First, the callback function (callback);

Second, event monitoring (Listener);

Third, the observer model;

Iv. Promise Objects

First, callback function (callback)

The most basic method of async

Suppose there are two functions, F1 and F2, which wait for the former to execute the result.

F1 ();

F2 ();

If F1 is a time-consuming task, consider rewriting F1 and writing F2 as the F1 callback function.

function F1 (callback) {  settimeout (function() {     //F1 code      callback ();    },+);  }

The execution code looks like this

F1 (F2);

In a solemn way, the synchronous operation becomes an asynchronous operation, F1 does not plug the program's operation, first executes the main logic of the program, and delays the execution of the time-consuming operation.

In fact, I understand it is very difficult, because the first language after college is C, then C + +, then Java, in the traditional function as a parameter input data , and use the return statement to return the value . Theoretically, there is a return statement at the end of the function that is structured as an input point and an output point. the essence of a function is the mapping of the implementation process between input and output.

However, when the implementation of a function is lengthy, do you choose to wait for the function to be processed or to use a callback function for asynchronous processing?

A: In this case, it becomes critical to use a callback function, such as an AJAX request. If the callback function is used for processing, Emma can continue to perform other tasks without having to wait. In real-world development, asynchronous calls are often used in JavaScript and are even recommended here.

 //  transfer function as a callback, the function is passed as a parameter  function   FN (a,b,callback1) { var    Num=math.ceil (Math.random () * (A-B) +b);     Callback1 (num);  //  pass result   10,20,function   "Random number" +num);});  //   
function foo () {  var a=10;   return function () {   a*=2;    return A;};} var f=foo (); F ();      // returnf ();     // return 40
Returning an inline anonymous function is a way to create a closure.

An example of a callback function for Ajax.

$.ajax ({URL:"Test.json", type:"GET", data:{username:$ ("#username"). Val ()}, DataType:"JSON", Beforsend:function(){           //Disable buttons to prevent duplicate submissions$ ("#submit"). attr ({disabled: "Disabled")}); }, Complete:function(msg) {//callback function called after the request is completed}, Error:function(msg) {//callback function called when a request fails} Success:function(msg) {//callback function called after the request succeeds}});

(1) callback function definition: function A as a parameter (function reference) passed to another function B, and this function B executes function A, we call the function a called the callback function, if there is no Name (function expression), we call it anonymous callback function.

(2) Advantages of callback function: simple, easy to understand and deploy.

Cons: not conducive to code reading, and maintenance, the high degree of coupling between the parts, the process will be very confusing, and each task can only specify a callback function.

Second, event monitoring

Use 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

Take F1 and F2 as an example. First, bind an event (in jquery notation) for F1.

F1.on (' Done ', F2);

The above code means that when the done event occurs in F1, the F2 is executed.

Then rewrite the F1:

function F1 () {    settimeout   () {///F1 task code   F1.trigger (' Done ');  },+);}

F1.trigger (' Done ') indicates that when execution is complete, the Do event is immediately triggered to begin execution of F2.

Advantages of this approach: it is easier to understand, can be bound to multiple events, each event can specify multiple callback functions, and can be decoupled, conducive to the implementation of modularity.

The disadvantage of this approach is that the entire program becomes event-driven and the running process becomes unclear.

Event Listener Method:

(1) OnClick method

element.onclick=function() {   //handler}

Pros: Writing compatibility to mainstream browsers

Disadvantage: Only the last event is added when the same element is bound to multiple events

For example:

element.onclick=Handler1;element.onclick=Handler2;element.onclick=handler3;

Appeal only Handler3 will be added to execute, so we use another method to add an event

(2) Attachevent and Addevenlistener methods

// ie:attacheventelment.attachevent ("onclick", handler1); Elment.attachevent ("onclick", HANDLER2); Elment.attachevent ("onclick", Handler3);

The above three methods are executed in sequence: 3-2-1;

// Standard AddEventListenerelment.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 represented by the inward, true is represented by the extroversion.

<div id= "Id1" > <div id= "Id2" ></div></div>document.getElementById ("Id1"). AddEventListener ("click",function() {console.log (' id1 ');},false);d Ocument.getelementbyid ("Id2"). AddEventListener ("click",function() {console.log (' Id2 ');},false);//Click Id=id2 Div, first output in Sonsole, first output id2, output id1document.getElementById ("Id1"). AddEventListener ("click",function() {console.log (' id1 ');},false);d Ocument.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

(iii) DOM methods AddEventListener () and Removelistenner ()

Addeventlistenner () and Removelistenner () represent functions that are used to assign and delete events. Both of these methods require three parameters, namely:

String (the event name), the function functions to trigger the event, specifying the time or phase (Boolean) of the event's handler function.

See for example (ii)

(d) Common time to add methods:

On:function(elment,type,handler) {   // Add event   return Element.attachevent? Elment.attachevent ("On" +type,handler): Elment.addeventlistener (Type,handler,false);}

The difference between bubbling event and event capture can be consulted: http:/www.cnblogs.com/chengxs/p/6388779.html

Third, the Observer pattern

The observer pattern is also called the Publish-subscribe pattern, which defines a one-to-many relationship that allows multiple observers to listen to a Subject object at the same time, and the state change of the Subject object notifies a number of observer objects so that they can automatically update themselves.

Advantages: 1, support simple broadcast communication, automatically notify all subscribed objects.

2. Once the page is loaded, the target object can easily have a dynamic association with the observer, increasing flexibility.

3. The abstract coupling relationship between the target object and the observer can be extended and reused independently.

Iv. Promise Objects (Promise mode)

(1) The Promise object is a specification, a pattern proposed by the COMMONJS Working Group, 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.

//Promisevarp=NewPromise (function(resolved))//processing is done here. Maybe you can use AjaxSetTimeout (function(){   varResult=10*5; if(result===50) {Resolve (50); }Else{Reject (NewError (' 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 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 standard way ECMAScript 6 manages 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 overwrite the following (using jquery implementations):

function F1 () {  var dfd=$.deferred ();  settimeout (function() {  ///F1 's task code    dfd.resolve ();}, ); 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). then (F3);

For example, specify the callback function when the error occurs:

F1 (). Then (F2). Fail (F3);

Furthermore, it has the advantage of having 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.

Front-End Basics (iv): JS asynchronous mode: 1, callback function, 2, event Listener, 3, observer mode, 4, Promise Object

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.