[book intensive reading] “JavaScript asynchronous programming” intensive reading notes sharing


Write it at the front

  • Book Introduction: this book describes the basic asynchronous processing skills, including PubSub, event mode, promises and so on. Through these skills, you can better deal with the complexity of large-scale web applications and quickly respond to the code. Understanding the asynchronous mode of JavaScript allows readers to write JavaScript programs with more reasonable structure, better performance and more convenient 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. In particular, we recommend JavaScript asynchronous programming.
  • !! Welfare: at the end of the article, there are pdf books, mind map notes, and download address packaged with the book code. To read all the articles in the book intensive reading series, please move to: recommended Collection – Javascript Book Intensive Reading Notes Series navigation

[book intensive reading]

The first chapter is an in-depth understanding of JavaScript events

1.1. Event scheduling

  • Javascript code is used not to be interrupted because code only needs to queue events during run time, which are not triggered until the end of the code run

1.2. Types of asynchronous functions

  • Each JavaScript environment has its own set of asynchronous functions
  • On the browser side, AJAX methods have an async option that can be set to false
  • stay Node.js The API methods synchronized in will be clearly marked on the name, such as fs.readFileSync
  • WebKit’s console.log The printout does not take a snapshot of the object immediately, 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 It’s strictly synchronized
  • When the same JavaScript process is running code, no JavaScript timing function can make other code run
  • When the setinterval scheduling event is set to 0, the trigger frequency of chrome and other browsers is about 200 times / s, and node is about 1000 times / second
  • When replaced by a while loop, the trigger frequency can reach 4 million times / second in chrome and 5 million times / second in node
  • More fine-grained timing is needed, which is used in node process.nextTick , using requestanimation frame (idea compatibility) in modern browsers

1.3. Writing asynchronous functions

  • The only way to confirm that a function is asynchronous is to review its source code
  • Some functions are asynchronous at some times, but not at other times
  • A large amount of time delay will cause huge calculation load
  • The fear of asynchronous recursion is that there is no limit to the number of times a delay can be triggered while waiting for the task to complete
  • Never define a function that potentially synchronizes and whose return value might be used for callback

1.4. Asynchronous error handling

  • JavaScript also allows exceptions to be thrown, which are then captured with a try / catch block
  • As a result of this, Node.js Callbacks in almost always accept an error as its first parameter, allowing the callback to decide on its own how to handle the error
  • Always remember that asynchronous errors originating from callbacks can only be handled inside callbacks
  • In the browser environment, windows.onerror You can catch exceptions, and if you return true, you can prevent the browser from default error handling behavior
  • In node, the uncaughtexception event of similar process object is caught incorrectly. Normally, the node application will exit immediately due to uncaught exception
  • But since node 0.8.4, the uncaughtexception event has been discarded
  • The domain object is an eventized object that converts 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 tempt us to add more features by adding more code, rather than implementing them as manageable, reusable pieces of code
  • By convention, avoid more than two levels of nesting of functions

Chapter 2 distributed events

  • Want to use distributed events: the butterfly of events occasionally flutters its wings, and the entire application triggers reactions everywhere
  • PubSub means publish / subscribe, mode to distribute events
  • Some concrete expressions of PubSub pattern: EventEmitter object of node, eventing model of backbone, and custom event of jQuery

2.1. PubSub mode

  • Almost all I / O in node is an EventEmitter object: file stream, HTTP server, 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 don’t need to happen immediately, and use a timing function to run the next task in the queue
  • PubSub simplifies the naming, distribution and stacking of events

2.2. Event model

  • As long as an object has a PubSub interface, it can be called an evented object
  • Each time an event on an object raises a series of events and eventually triggers the same event on the object itself, resulting in an event loop
  • The eventing model provides us with an intuitive way to convert application state changes into events

2.3. JQuery custom event

  • JQuery simplifies the migration of powerful distributed event systems to any web application
  • JQuery provides a non bubbling triggerhandler method
  • JQuery’s custom events allow DOM related events to be expressed directly through DOM without having to copy the state of DOM changes to other parts of the application


  • The PubSub model is particularly unsuitable for one-time events
  • The tool for solving one-time event problems is called promise

Chapter 3 promise object and deferred object

A brief history of promise

  • Promise object, like the EventEmitter object, allows you to bind any number of processors to the same event (heap Technology)
  • The biggest advantage of using promise objects is that new promise objects can be easily derived from existing promise objects
  • In general usage, promise, deferred and future can be regarded as synonyms

3.2. Generate promise object

  • To be exact, deffered is a superset of promise. It has one more key feature than promise, which can be triggered directly
  • Again, each deferred object contains a promise object, and each promise object represents a deferred object
  • AJAX is a great use case for demonstrating promise: every call to a remote server either succeeds or fails, and we want to deal with both in different ways

3.3. Passing data to callback function

  • When a deferred object is executed or rejected, any parameters provided are forwarded to the corresponding callback
  • Resolve / reject can directly pass its context to the callback it triggers

3.4. Progress notice

  • Jquery1.7 adds a new callback progress that can be called countless times for the promise object
  • In summary, the promise object accepts three callback forms: done, fail, and progress

3.5. Merge promise objects

  • One of the most common use cases of promise object logical merging technique is to determine when a set of asynchronous tasks are completed

3.6. Pipeline connection future

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

3.7. Comparison between jQuery and promises / A

  • JQuery uses resolve as the opposite of fail, while promise / a uses full. In promise / a specification, promise objects are executed whether they have been fulfilled or failed

3.8. Replace callback function with promise object

  • Ideally, any function that starts executing an asynchronous task should return a promise object
  • Promise helps to smooth out spaghetti callbacks, and it’s also because promise can easily coordinate this type of asynchronous task

Chapter four Async.js Workflow control based on

4.1. The order of asynchronous workflow

  • Ordinary asynchronous code can’t guarantee that the callbacks will be triggered in the order in which they are made

4.3. Async.js Task organization technology based on

  • Async.js This method solves the problem of how to apply an asynchronous function to a data set
  • Operation of asynchronous function sequence: async.series and async.waterfall
  • What’s convenient is that Async.js Results are passed to the completion event handler in the order of the task list, not in the order in which they were generated
  • Async.js The kernel and soul of: provide simple and time-saving tool functions for the most common asynchronous scenarios

4.4. Dynamic queuing technology of asynchronous workflow

  • async.queue The underlying philosophy of DMV is reminiscent of the dynamic management view of DMV

Chapter 5 multithreading technology of worker object

5.0. Write at the front

  • Events can replace a special kind of multithreading, that is, the application process can be divided into multiple parts to run simultaneously (or realized by interrupt technology, or realized by multiple CPU cores)
  • Although it’s not ideal to run on only one thread, it’s worse to be naive and distribute applications directly to multiple cores
  • Interacting with different threads is the same as I / O in JavaScript
  • Multiple threads within the same process can share state, while independent processes cannot
  • In a JavaScript environment, concurrent code run by a worker object never shares state

5.1. Web version of the worker object

  • The primary goal is to process complex calculations without compromising DOM responsiveness
  • Several potential uses: decoding video, encrypting communication, parsing Web Editor
  • For similar reasons, the worker object cannot see the global window object and any object of the main thread and other worker threads
  • The object sent by PostMessage will be serialized and deserialized transparently. Think about it JSON.parse And JSON.stringify
  • The worker object is free to use XMLHttpRequest
  • There is also an importscripts function that loads and runs the specified script synchronously

5.2. Node version worker brought by cluster

  • After node0.6, it introduces a method that supports multiple processes to bind to the same port API:cluster (cluster)
  • Usually, cluster is used to divide a process according to each CPU core for the best performance
  • The node version of the worker object is created by cluster.fork () load the same script running itself as a separate process again
  • The browser can reduce any redundant threads to background tasks, while the node server should reserve computing resources to guarantee its main task of request processing
  • The most famous Magic: when multiple worker objects try to listen on a TCP port, node uses internal messages to allow sharing of that port
  • Similarly, the cluster object has a main thread and multiple worker threads based on 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 such as redis

Chapter 6 asynchronous script loading

  • You need to divide and rule the scripts. Those responsible for making the page look better and better should be loaded immediately, while those that can be loaded later will be loaded later

6.1. Limitations and supplementary notes

  • Try to avoid using inline technology
  • Do not use document.write
  • Just know document.write The go to statement is equivalent to a go to statement

6.2. Recognition of script tag

  • There are two new types of script tags in modern browsers: classic and non blocking
  • It is popular to put scripts at the end of the page’s body tag. On the one hand, users can see the page faster, on the other hand, they can actively and intimately contact DOM without waiting for events to trigger themselves
  • Defer reminds us of the orderly queuing scenario of quietly waiting for documents to load, and async reminds us of chaotic anarchy
  • If a script uses both defer and async, async will override defer in those browsers that support it at the same time

6.3. Programmable script loading

  • There are two reasonable ways to grab and run server scripts: generate Ajax requests and handle responses with Eval functions; and insert script tags into dom
  • require.js Powerful toolkit can automatically smooth out even the most complex script dependency graph with AMD technology
  • If you require scripts to be loaded based on conditions, consider a script loader like yepnope. If your site has a large number of interdependent scripts, consider require.js

Write it at the back

  • Pdf book, mind map for notes, package with book code, download address: https://pan.baidu.com/s/1WMzAciLMfTasiWFQjz4ftA (extraction code: wd01)
  • Purchase address of paper book Jingdong: https://u.jd.com/e0BT68 (paper books are recommended for learning)
  • In order to facilitate the mobile phone to see, I will post these notes to the official account “three pie four” later, I can scan code to pay attention to it, welcome to pay attention.
    [book intensive reading]