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

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.

callback

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, (=&gt); alert (‘1000 milliseconds) after me! ‘)

It’s the callback function.

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) {)

Fun2 (value1, function (Value2) {

Fun3 (Value2, function (value3) {

FUN4 (value3, function (value4) {

/ /…

});

});

});

});

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 the library, Pu Ling

To a great extent,

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

There are no nested callbacks in the world.

. – fengmk2

EventProxy

It is to solve the nesting.

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;

Var result = {};

$.get (‘http://demo1’, function (data) {

Result.data1 = data;

Count++;

Handle ();

});

$.get (‘http://demo2’, function (data) {

Result.data2 = data;

Count++;

Handle ();

});

$.get (‘http://demo3’, function (data) {

Result.data3 = data;

Count++;

Handle ();

});

Function handle () {

If (count = = = 3) {

/ / follow up operation result

}

}

After the use of EventProxy:

Var proxy = new eventproxy ();

Proxy.all (‘data1_event’,’data2_event’,’data3_event’, function (data1, data2, data3) {

/ / follow up operation result

});

$.get (‘http://demo1’, function (data) {

Proxy.emit (‘data1_event’, data);

});

$.get (‘http://demo2’, function (data) {

Proxy.emit (‘data2_event’, data);

});

$.get (‘http://demo3’, function (data) {

Proxy.emit (‘data3_event’, data);

});

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.

It’s the publisher, proxy.all

The subscriber is the subscriber, but EventProxy’s all API can subscribe to multiple messages at the same time and process all the messages, which is an extension of the common publish / subscribe pattern.

The specific implementation principle of EventProxy comes from the event module of Backbone, and interested GitHub can go to it.

Check it out.

Promise

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 ().

I don’t know what it means, I think it’s high-end. At that time, leader and I said, promise is very simple, that is, give you a commitment first, and then finish the next step. It always passes a promise object.

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+

. Now in the ECMAScript 2015 specification, JavaScript supports native promise (of course, if you want compatibility), use Babel.

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) {

/ / little two promises to give you a bowl of beef noodles

If (success) {

/ / resolve beef noodles for you

Return resolve (data);

} else {

/ / the kitchen beef is sold out, reject made a mistake for you.

Return reject (data);

}

});

Promise.then (function (data) {)

/ / / success, eat it

Console.log (data);

}, function (ERR) {

/ / failure, I want to refund!

})

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 ()

The method is similar to the all of EventProxy, but it returns a promise object. When all promise objects are successful, they will enter the completed state. If one of the promise objects has failed, Promise.all

It will also enter a state of failure. You can view https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all in detail.

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. It’s more than a normal function.

Number, *

The number appears between the keyword function and the function name, if it is an anonymous letter.

Leave a Reply

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