[Book intensive reading] "MVC-based JavaScript Web rich application development" intensive reading notes sharing

Write in front

  • Book introduction: "JavaScript asynchronous programming" tells basic asynchronous processing skills, including PubSub, event mode, Promises, etc., through these skills, you can better deal with the complexity of large-scale Web applications, interactive and fast response code. Understanding the asynchronous mode of JavaScript allows readers to write JavaScript programs with more reasonable structure, better performance, and easier maintenance.
  • My brief comment: js asynchronous programming popular science book, the content is more comprehensive but not deep enough. As a front-end development, it is very important to understand the asynchronous processing mechanism and optimize asynchronous code, especially recommend "JavaScript asynchronous programming".
  • ! ! Welfare: At the end of the article, there are pdf books, mind maps for notes, and download addresses for packaged with the book code.

Chapter 1 has a deep understanding of JavaScript events

1.1. Event scheduling

  • JavaScript code is used to be uninterrupted, because the code only needs to queue events during runtime, and these events will not be triggered before the end of the code.

1.2. Types of asynchronous functions

  • Each JavaScript environment has its own set of asynchronous functions
  • On the browser side, the Ajax method has an async option that can be set to false
  • API methods synchronized in Node.js will be clearly marked on the name such as fs.readFileSync
  • WebKit's console.log printout does not immediately take a snapshot of the object, only a reference to the object is stored, and the snapshot is not printed until the code returns to the event queue
  • Node's console.log is strictly synchronized
  • When the same JavaScript process is running code, no JavaScript timing function can make other code run
  • SetInterval scheduling event is set to 0, Chrome and other browsers trigger frequency is about 200 times / second, node is about 1000 times / second
  • When replaced with a while loop, the trigger frequency in Chrome will reach 4 million times / second, and will reach 5 million times / second in node.
  • Need more fine-grained timing, use process.nextTick in node, and requestAnimationFrame in modern browsers (idea compatibility)

1.3. Writing of asynchronous functions

  • The only way to confirm whether a function is asynchronous or not is to review its source code
  • Some functions are asynchronous at some times, but not at other times
  • A large amount of delay will cause huge calculation load
  • Asynchronous recursion is a little scared, that while waiting for the task to complete, the number of delays that can be triggered is unlimited
  • Never define a function that is potentially synchronous and whose return value may be used for callbacks

1.4. Handling of asynchronous errors

  • JavaScript also allows exceptions to be thrown and subsequently captured with a try / catch block
  • Because of this, callbacks in Node.js almost always accept an error as their first parameter, which allows the callback to decide how to handle the error itself
  • Always remember that asynchronous errors originating from the callback can only be handled inside the callback
  • In the browser environment, windows.onerror can catch exceptions, if it returns true, it can prevent the browser's default error handling behavior
  • In node, the uncaughtException event of a similar process object catches an error. Under normal circumstances, the node application will immediately exit due to an uncaught exception
  • But since Node0.8.4, the uncaughtException event has been abandoned
  • The domain object is an event object, which converts the throw into an error event

1.5. De-nesting of nested callbacks

  • The most common anti-pattern approach is to nest callbacks inside callbacks
  • Nested callbacks lure us to add more features by adding more code instead of implementing these features as manageable and reusable code fragments
  • By convention, please avoid nesting more than two levels of functions

Chapter 2 Distributed Events

  • Hope to use distributed events: the butterfly of the event occasionally flaps its wings, and the entire application triggers reactions everywhere
  • PubSub means publish / subscribe, mode to distribute events
  • Some specific expressions of PubSub mode: Node's EventEmitter object, Backbone's event model, JQuery's custom event

2.1. PubSub mode

  • Almost all I / O in Node are EventEmitter objects: file streams, HTTP servers, and even the application process itself
  • The event handler itself cannot know whether it is running from the event queue or from the application code
  • Maintain a queue for things that do not need to happen immediately, and use a timing function to run the next task in this queue regularly
  • PubSub simplifies the naming, distribution, and accumulation of events

2.2. Event Model

  • As long as the object has a PubSub interface, it can be called an event object
  • Each time an event on an object triggers a series of events and eventually triggers the same event on the object itself, the result is an event loop
  • The event-based model brings us an intuitive way to transform application state changes into events

2.3. JQuery custom event

  • jQuery simplifies the migration of a powerful distributed event system to any web application
  • jQuery provides a non-bubbling triggerHandler method
  • jQuery's custom events allow DOM-related events to be expressed directly through the DOM, without having to copy the state of the DOM changes to other parts of the application

summary

  • PubSub mode is not particularly suitable for one-time events
  • The tool used to solve the one-time event is called Promise

Chapter 3 Promise objects and Deferred objects

3.1. A brief history of promises

  • Promise objects are the same as EventEmitter objects, allowing any number of processors to be bound to the same event (stacking technology)
  • The biggest advantage of using Promise objects is that you can easily derive new Promises from existing Promise objects
  • In general usage, the three words Promise, Deferred and Future can be roughly regarded as synonyms

3.2. Generate Promise object

  • To be precise, Deffered is a superset of Promises. It has one more key feature than Promises and can be triggered directly
  • To reiterate: each Deferred object contains a Promise object, and each Promise object represents a Deferred object
  • Ajax is a great use case for demonstrating promises: every call to a remote server succeeds or fails, and we want to handle these two situations in different ways

3.3. Passing data to the callback function

  • When the Deferred object is executed or rejected, any parameters provided will be forwarded to the corresponding callback
  • resolve / reject can directly pass its context to the callback triggered by itself

3.4. Progress notification

  • A new callback progress can be called for Promise object in jQuery1.7
  • In summary, the Promise object accepts 3 callback forms: done, fail, progress

3.5. Merging of Promise objects

  • The logical merge technique of Promise objects has one of the most common use cases: determining when a set of asynchronous tasks are completed

3.6. Pipeline connects the future

  • JavaScript is often unable to conveniently execute a series of asynchronous tasks, one of the main reasons is that it is impossible to attach a processor to the second task before the end of the first task
  • jQuery1.6 adds pipe method to Promise object
  • promise.promise() === promise

3.7. Comparison between jQuery and Promises / A

  • jQuery uses resolve as an antonym for fail, while Promise / A uses fulfill. In the Promise / A specification, the Promise object is executed whether it has been fulfilled or failed

3.8. Use Promise objects instead of callback functions

  • Ideally, any function that starts performing an asynchronous task should return a Promise object
  • Promises greatly help smooth pasta-style callbacks, and because Promise can easily coordinate this type of asynchronous task

Chapter 4 Workflow Control of Async.js

4.1. The order of asynchronous workflow

  • Ordinary asynchronous code simply cannot guarantee that the callbacks that are called are triggered in the order in which they are called

4.3. Async.js task organization technology

  • The data collection method of Async.js solves the problem of how an asynchronous function is applied to a data set
  • Running of asynchronous function sequence: async.series and async.waterfall
  • It is convenient that Async.js passes the results to the completion event processor in the order of the task list, rather than in the order in which these results are generated
  • The core and soul of Async.js: provide simple and time-saving tool functions for the most common asynchronous scenarios

4.4. Dynamic queuing technology for asynchronous workflow

  • The underlying basic idea of ​​async.queue is reminiscent of DMV dynamic management views

Chapter 5 Multithreading Technology of Worker Objects

5.0. Write in front

  • Events can replace a special kind of multi-threading, that is, the application process can be split into multiple parts to run simultaneously in multi-threading technology (either through interrupt technology virtual implementation, or through multiple CPU cores)
  • Although running on one thread is not ideal, naively distributing applications directly to multiple cores is even worse
  • The way to interact with different threads is exactly the same as I / O operations in JavaScript
  • Multiple threads within the same process can share state, but processes that are independent of each other cannot
  • In a JavaScript environment, concurrent code run by worker objects will never share state

5.1. The web version of the worker object

  • The primary goal is to handle complex calculations without compromising DOM responsiveness
  • Several potential usages: decode video, encrypt communication, parse web editor
  • For similar reasons, the worker object cannot see the global window object and any objects of the main thread and other worker threads
  • Objects sent via postMessage will be serialized and deserialized transparently, think about JSON.parse and JSON.stringify
  • Worker objects can use XMLHttpRequest at will
  • There is also an importScripts function that can load and run the specified script synchronously

5.2. Node version of workers brought by cluster

  • After node0.6, an API that supports multiple processes binding to the same port is introduced: cluster (cluster)
  • Usually in pursuit of the best performance, cluster is used to differentiate a process according to each CPU core
  • The node version of the worker object is reloaded by cluster.fork () to run the same script as an independent process.
  • The browser can downgrade any extra threads to background tasks, and the node server should reserve computing resources to ensure the main tasks of its request processing
  • The most famous magic: when multiple worker objects try to listen to a TCP port, node uses internal messages to allow sharing the port
  • Similarly, the cluster object has a main thread and multiple worker threads, based on some events with serialized objects or attached strings
  • In order to minimize the communication overhead between threads, the shared state between threads should be stored in an external database like Redis

Chapter 6 Asynchronous script loading

  • Scripts need to be divided and conquered. Scripts that are responsible for making the page look better and better should be loaded immediately, and those that can be loaded later will be loaded later.

6.1. Limitations and supplementary instructions

  • Please try to avoid using inline technology
  • Do not use document.write
  • Just know that document.write is equivalent to the GOTO statement when manipulating the DOM

6.2. Recognition of the script tag

  • The script tags in modern browsers are divided into two new types: classic and non-blocking
  • It is popular to put the script at the end of the body tag of the page. On the one hand, users can see the page faster, on the other hand, they can actively touch the DOM without waiting for events to trigger themselves
  • defer reminds us of an orderly queuing scenario that quietly waits for documents to load, then async will remind us of chaotic anarchy
  • If a script uses both defer and async, in those browsers that support it at the same time, async will overwrite defer

6.3. Programmable script loading

  • Two reasonable methods to grab and run server script: generate Ajax request and use eval function to process response; insert script tag into DOM
  • The powerful toolkit of require.js can automatically smooth out even the most complex script dependency graph with AMD technology
  • If you need to load scripts based on conditions, please consider a script loader like yepnope. If the site has a lot of interdependent scripts, please consider require.js

Write in the back

Guess you like

Origin www.cnblogs.com/yzsunlei/p/12716884.html