JS Reading notes: "JavaScript Framework Design"-The 12th chapter asynchronous processing

Source: Internet
Author: User

First, what is asynchronous

The process of performing a task can be divided into two parts, initiating and executing.

Synchronous Execution Mode : After a task has been initiated, it must wait until the task executes and returns the result before the next task is executed.

Asynchronous Execution Mode : The task executes without waiting for the task to complete, but executes the next task immediately, and receives a notification when the task execution is complete.

In the face of frequent IO operations, asynchronous execution mode provides greater concurrency in the same hardware resource conditions, which means greater throughput.

However, the asynchronous execution pattern breaks down the inherent way of thinking, and the initiation of tasks and the execution of tasks are separated, thus improving the complexity of programming.

multithreaded, multi-process can implement asynchronous mode.

Second, from the callback to the hell.

I believe everyone has heard of the "Callback Hell", which makes the egg ache by the unavoidable asynchronous execution pattern side effects. Example:

SetTimeout (function () {setTimeout () {setTimeout (function () {         setTimeout (function () {          +     ))  

Because JS is implemented asynchronously through asynchronous execution mode, it inevitably encounters the awkward situation of asynchronous task nested, and callback hell is the concrete manifestation of asynchronous task nesting.

Callback Hell not only makes the code difficult to maintain, but also increases the difficulty of debugging, word-an unavoidable egg ache: (

Iii. those programmes to relieve callback hell

Since the callback hell is so not elegant but unavoidable, is there any abstract way to deal with the pain of the callback?

Before looking for the medicine, we need to understand the reason for the formation of a callback to hell, from a local point of view is to start an asynchronous task must meet some preconditions, from the global perspective is the asynchronous execution mode of process Control . In fact, in the synchronous execution mode also exists in the same situation, but synchronous execution mode and we usually think the same way, so it is natural to meet the preconditions before performing the synchronization task is a logical thing, nor how much feeling. But in the asynchronous task, it becomes a prominent problem. Think about it, if the asynchronous task a-> asynchronous task b-> Asynchronous task C is the predecessor of an asynchronous task, then their relationship is actually synchronous execution, but the code expression is forced to use the asynchronous encoding pattern, the difference between the intrinsic relationship and the form of expression makes the famous callback hell.

The process control in synchronous execution mode has the if... elseif ... Else , while, and try... Catch: finally 。 Our ultimate goal is to express the Process control in asynchronous execution mode in a way that can be used. Obviously this is doomed to be a pseudo proposition without changing the JS syntax. And what we can do is keep approaching.

And @ Pauling's eventproxy is one of the tools that alleviates the pain of the callback function.

As an event system, Eventproxy provides a constrained event-triggering mechanism through the event subscription methods such as after, tail, and "constraints" corresponding to "preconditions", so we can use this constrained event-triggering mechanism as a process control expression in asynchronous execution mode.

For example, Task C is now required to execute successfully after task A and task B.

/*Synchronous Execution Mode*/Try{  varRESULT4A =Execa ()varRESULT4B =EXECB ()varRESULT4C =EXECC ()}Catch(e) {}/*Asynchronous Execution Mode*///1. Callback function mode--callback hell appears! Execa (function () {EXECB (function () {EXECC ()})})//2. EventproxyvarEP = Eventproxy.create ('a','b', EXECC) ep.fail (function $noop $ () {}) Execa (Ep.done ('a')) EXECB (Ep.done ('b'))

You can see that the number of callback functions is not reduced when using eventproxy, but the callback hell is gone (verifying that the callback hell is not caused by the callback function, but rather by the process control in asynchronous execution mode)

But because Eventproxy uses the event mechanism to do the process control, and the event mechanism advantage is to reduce the coupling degree of the module, but from another point of view will make the whole system structure loosely difficult to see the main module, so through the event mechanism to achieve process control inevitably lead to code structure loosely and logically discrete, But this can be a good form of organization to make the code structure more closely.

Iv. Knowledge of Promise

The promise here refers to the promises/a+ specification that has been ES6 into the SAC and its implementation. Examples of Use:

var New Promise (function (resolve, reject) {  resolve ("test")}) P  . Then ( Function (val) {    console.log (val)    return1  }, function (reason) {  })  . Then (function (val) {    console.log (val)  }, function (reason) {  })

I began to know the existence of promise from the promise method of jquery.deferred. But what kind of a mechanism does promises/a+ describe?

1. Imagery--api

promises/a+ Specifies that the promise status is pending (default), fufilled, or rejected, where the state can only be from pending->fulfilled or pending->rejected, and can subscribe to status change events via then and catch. The result of the callback function execution of the state change event affects the state of the next promise instance in the promise chain. Additionally, additional information can be carried when triggering the promise state change, and the additional information will be passed along the promise chain until it is received by an promise event callback function. Promise also provides Promise.all and promise.race two helper methods to implement the logical relationship with or, providing promsie.resolve to convert thenable objects to promise objects.

2. Process Control

Through promise we can successfully disengage from the callback hell. Such as:

var execap = promise.resolve ({Then:execa})  =  promise.resolve ({THEN:EXECB}) Promise  . All (Execap, EXECBP)  . Then (EXECC)

This is also the function that promise is widely recognized by everybody.

3. Trust mechanisms

An in-depth understanding of promise five, written by LABJS authors, is a more profound interpretation of promise from another perspective. When we need to control local function modules through a third-party tool library or interface, a trust mechanism is established through promise to ensure that local functional modules are manipulated by third parties within a predictable range.

Proimse, the LEGO Building block for library developers, needs to provide a higher level of abstraction in the face of ordinary developers.

V. Understanding Generator Function

The Generator function is a new feature introduced by ES6-generator functions. By combining promise and generator function, we can implement the process control in the mode of asynchronous execution by using the way of expression!!!

Vi. Related Notes

JS Magic Hall: Analysis of the source code understanding promises/a Code

"Front-end translation: promises/a+ specification"

"JS Magic Hall: jsdeferred Source Code Analysis"

"JS Magic Hall: jquery.deferred (jquery1.5-2.1) source Analysis"

"JS Magic Hall: mmdeferred Source Code Analysis"

"JS Magic Hall: ES6 new features--generatorfunction Introduction"

"JS Magic Hall: Native Promise only source analysis"

Seven, Ipromise

Ipromise is the implementation of the Promises/a+ specification for asynchronous processing edge development, and the support for generator function has been implemented internally. After 3 global refactoring is now in v0.8.2, I think the code structure now read more fluent, and the API is fixed, is expected to be a patch in the future. Welcome everyone fork to play [email protected]

Viii. Summary

This time I to the "JavaScript Framework Design"-The 12th chapter asynchronous processing of learning and practice summary, if there are flaws and shortcomings, please correct, add, thank you!

Respect the original, reprint please indicate from: http://www.cnblogs.com/fsjohnhuang/p/4296831.html ^_^ Fat Boy John

JS Reading notes: "JavaScript Framework Design"-The 12th chapter asynchronous processing

Related Article

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.