One, callback callback function
That is, the relationship between function F1 and function F2 is F1 (F2 ());
F2, as a callback function for F1 (), starts executing F2 during F1 execution, first executing the main logic of the thread, and putting the time-consuming tasks behind.
The advantages of the callback function are simple, easy to understand and deploy
The disadvantage is that it is not conducive to the reading and maintenance of the code, the high coupling between the parts (coupling), the process is confusing, and each task can only specify a callback function.
Second, event monitoring
Event snooping is completely unrelated to the order of the Code, depending only on whether the event occurred, such as F1.bind ("click", F2), even if the F1 is F2 executed when the click is taken. An event can bind multiple listener functions.
The entire program becomes event-driven, and the running process becomes very unclear.
Three-Signal publish/Subscribe
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) Once the execution is complete.
Jquery.unsubscribe ("Done", F2);
This method is similar in nature to "event monitoring", but is 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.
Iv. promises objects
The promises object is a specification proposed by the COMMONJS workgroup to provide a unified interface for asynchronous programming.
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);
The callback function becomes the chain style, the process of the program can be seen very clearly, and there is a set of matching methods, can achieve many powerful functions.
For example, specify multiple callback functions:
F1 (). Then (F2). then (F3);
For example, specify the callback function when an error occurs:
F1 (). Then (F2). Fail (F3);
Moreover, it has the advantage of having none 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 signal. The disadvantage of this method is that it is relatively difficult to write and understand.
The asynchronous programming method of JavaScript