The front end is from the beginning to the re – entry – Asynchronous

What is

asynchronous? That’s about the language of JavaScript.

What is asynchronous? That’s about the language of JavaScript.

Born in 1995, JavaScript was designed as a single thread as the script language of browser at that time. That is to say, it can only do one thing at the same time. Why is it like this? Imagine how the browser should respond when the JavaScript is multithreaded, and the user adds content to a node and deletes the node in a thread.

JavaScript solves the complex synchronization problem in browsers with single thread, but a single thread must introduce a concept, that is, the task queue. In a civilized society, there are many demands and few items, so we must queue up. When a task ends, the next task begins. Does it seem perfect, but is there any defect? Yes, we have. For example, when you go to your favorite noodle shop, you find a long queue at the door, but the seats inside are empty. The process of this noodle shop is: customer order, small second and down – customers and small second eyes stare eyes – the kitchen gives the food to the second, the second gives the customer – the customer comes to the table with the food – the end.

Such a process is the most important place is the customer and small eyes stare in the stage, time is wasted on it, so a long queue of people are not satisfied. How should we optimize it?

After discussing with the noodle shop owner, this optimization scheme is given.

Customer order, small second and down – small two give a brand to customers, representing the number of customers – customers sit on the table and start to chat with the mobile phone – the kitchen to the second, the second according to the number to the customer – end.

As soon as the boss heard this well, there were fewer people waiting in line, and the efficiency of the second grade was higher, so he invited me to eat the best beef noodles they had.

This is asynchronous, the time-consuming operation is executed elsewhere, and the result is put back to the queue after execution. In this way, other operations can be done at this time, rather than blocking here. In other words, how does JavaScript realize asynchronous? It’s the callback function.


The callback function is called callback in English, and it is simply to call the callback function after a task is executed, and the callback function can get the result of this task. In the JavaScript world, there is a callback function everywhere. The simplest is the setTimeout method.

SetTimeout (() => alert (‘1000 millisecond after the emergence of me! “), 1000)

The above code is actually waiting for 1000 milliseconds, () => alert ('1000 millisecond after me! ")

() => alert (I appeared after’1000 milliseconds! ‘)

The callback function is easy to use and well understood, but how to use multiple asynchronous data together? What is the necessary condition for an asynchronous task? What is the result of another asynchronous task? Some people began to write nested callback, commonly known as the callback of Pyramid.

Fun1 (function (value1) {)

This code is very common in high frequency asynchronous processing such as node. It’s very well written. After a day, you look back at your code, what are you writing about?

At this point, we will embark on a road to find the best solution for asynchronous processing of front-end. As the title says, you think you are getting started. Actually, there is another door in front of you, commonly known as Moore’s law.

EventProxy and publish / subscribe patterns

As the author of this library is Pu Ling


There is no such thing as deep nesting of callbacks in the world. Jackson Tian

There is no nesting callback in the world, and many people write, and there is }}}}}}}}}}}}.





If you want to get data from several addresses asynchronously and process all the data after getting all the data, the simplest way to write a counter in addition to the callback to Pyramid is to write a counter.

Var count = 0;

After the use of EventProxy:

Var proxy = new eventproxy ();

This is a typical event publish / subscribe mode. Let’s throw away the code and start with what is publish / subscribe mode.

Publish / subscribe mode is also called observer mode. The publish / subscribe mode defines a one to many dependency relationship that allows multiple subscribers to listen to a topic object at the same time. The subject object will notify all subscriber objects when their state changes, so that they can update their status automatically.

In a word, your favorite chef’s chef returned home to marry a daughter-in-law, and the beef noodles made by the new chef did not suit your taste, so you called the restaurant every day to ask the old chef to come back. The boss could not bear it any more. Every day he received a similar phone call to get mad and asked me how to deal with it. I said simply, write down the phone call of everyone who wants to eat the beef chef, and tell them that the old chefs come and text them. So the boss’s phone was finally quiet.

The above example of mental retardation is publish / subscribe mode, which is often encountered in our daily life. The boss is the publisher, the customer is the subscriber, the customer subscribes the information which the old chef comes back, when the old chef comes back, the boss releases this news to the customer. What are the benefits of a publish / subscribe pattern? It can decouple logic, publishers need not care about the specific business logic of subscribers, and do not care about how many subscribers, they can deliver messages to subscribers. Subscribers do not have to ask the publisher if they have any news, but they will get the message he wants at the first time.

Back to EventProxy, proxy.emit ('data1_event', data) in the above example.

Proxy.emit (‘data1_event’, data)


The specific implementation principle of EventProxy comes from the event module of Backbone, which is interested in going to its github



What is promise? The Chinese meaning of promise is commitment.

I remember that my first contact with promise was in my first angular project, when the code of the project contained many promise.then ().Then () .

Promise.then ().Then ()

At that time, I naively assumed that promise only had angular, and later discovered that $q in angular was just one of the promise implementations. The entire code base of AngularJS relies heavily on Promise, including the framework and the application code you write with it.

Go back to the point. Many third party libraries have implemented promise, such as when, $q for angular, etc. They follow the same specification: Promises/A+


The so-called Promise is a container that holds the result of an event that will end in the future (usually an asynchronous operation). A promise may have three states: incomplete, completed, and failed. The state of a promise can never be completed or transferred to completion or failure. It can not be converted backward, and has been completed and failed. At the same time, it is important to note that promise objects are passed between them.

Take a chestnut: you ordered a meal at the noodle shop, and Xiao 2 gave you a meal card. This card is no use for you. You can neither eat nor sell money, but you have to pay for the meal, which is an unfinished state. When the kitchen is ready, Xiao two will take the beef noodle for your meal card, and you get the beef noodles you want to eat. This is the state that has been completed. The beef in the kitchen is sold out, and the second runner comes to apologize to you for letting you change a bowl of noodles or withdraw your money, which is the failure and the handling after failure. Failure has not been directly converted to completion. Do you want to change a bowl or go through the promise process, which is completed and failed and can not be converted to each other.

After knowing the theory of promise, let’s look at the original promise:.

Var promise = new Promise (function func (resolve, reject) {

The variable promise here is an instance of Promise’s object. If there is no error after the logic process, you can get the beef noodle in the first callback function in then, and if there is a mistake, you will do the wrong processing in the second callback function in the then.

Promise also provides a Promise.all () .

Promise.all ()



The biggest advantage of promise is that it solves the problem of deep nesting of callbacks through chain calls. It looks elegant and easy to understand and use. But do you think this is all about JavaScript asynchronous programming?

The CO of Generator and TJ

The Chinese meaning of Generator is a generator. In the JavaScript world, functions are not suspended after being executed, only the state of “invoked” and “not invoked”. What happens when the function can be suspended?

Generator is the function that can be suspended. Its essence can be understood as a special data structure. Compared with ordinary functions, it has a *.



So how does it implement a pause? Through the yield keyword and next method in the function. Let’s look at an example to understand the writing method briefly.

Var g = function* (a, b) {

Let’s look at the following example step by step.

1. first, we create a Generator function named G.

2. instantiate this function, named generator. The generator at this time is a Generator object, and he has a next method. When you do not call next, the Generator function is suspended until it is executed internally to the first yield.

3. when we first called () ()

{value: 3, done: false}

4. the second call is like above. When the third call is made, the Generator function has no yield keyword, so the done returned is true.

It is important to note that .next ()

.next () ()

Var g = function* (a, b) {

This example is similar to the previous one, except that we added yield to the variable sum. When the first implementation of () () ()

{value: 3, done: false} (“hello”) (“hello”)

{value: undefined, done: true}

Var sum = “hello”

Console.log (sum)


In this way, data can be transmitted dynamically, making code logic more flexible and at the same time capable of achieving our goal: asynchronous optimization. How do I use Generator for asynchronous? The first thing you can think of is to get the value passed through (data) after asynchronous processing. (data)

Var promise = new Promise (function func (resolve) {{

In this example, I first created a promise to simulate asynchronous requests, and then yield promise in the Generator function. The first execution of () () () (data)


Although asynchronous is a bit like synchronization now, do you think that manually calling () after example is very cumbersome and ugly? It’s not ugly or ugly.

Can you put it in a simple way? Yes. Next I want to introduce the co library written by TJ, a famous programmer. The co library is a Generator based function library. The main purpose is to automatically call .next () .

.next ()

As early as the Generator function of CO, only one trunk function was yield, 1.1.0 added promise support after 1.1.0, and later slowly began to support generators, generator functions, object, array.

Var co = require (‘co’);

Save the manual call to .next () ()

.next ()

Since the co function returns a promise object after the 4.0.0 version, you can add callbacks:

Var co = require (‘co’);

In the earlier version (1.4.0) Co provided a join.


/ / array

Co also allows you to use try/catch in the function body.



It should be noted that Generator is a method of ES6. But now node is released to version 7, and it can be directly supported. Please use Babel at the front end. In addition, if you just try it, you can turn on the chrome console. Because Chrome is the V8 kernel, you can use Generator and promise directly.


Earlier, we talked about Co. Is there any official implementation of such a good asynchronous program? Congratulations, in this era of rapid evolution of JavaScript, there is a similar plan for the government. This is async/await.

This program that appears in ES7 is actually the syntax sugar of Generator. Let’s take a look at the following example:

Const promise = new Promise (resolve) => {

Is it the same as co 10 Fen! The only difference is the *




.next ()

If we want multiple asynchronous concurrency execution, similar to that in EventProxy, we can combine Promise.all


Const promise1 = new Promise (resolve) => {

Compared with Generator, async/await is semantically more clear, async




Such a cool syntax to use, in the node version of the 7 version has been supported by the original, in the front end can be compiled by Babel to achieve. Of course, the universal chrome console can also be used directly.


I heard Rx.js for the first time at Ning JS Conference (forgive me for being ignorant), which is also a good asynchronous processing plan. After that, write an introduction to Rx.js. There are so many asynchronous solutions in the front end, but in the final analysis, it is because people are afraid of callback. These solutions have a common feature, that is, more and more like synchronous code, and the advantage is that the code is more readable, and the thinking doesn’t jump with the callback jump. To conclude, this article is only an introduction, and does not involve specific implementations. If we want to learn them well, we need to go deep into the code to understand their thoughts behind them.

Reference resources



Leave a Reply

Your email address will not be published. Required fields are marked *