This article tags:
javascript native JavaScript advantage javascript asynchronous JS asynchronous Operation callback function
TensorFlow
REST server Introduction
JS Asynchronous Operation , is already a commonplace topic, the article on this topic casually Google can see a lot of. So why do I have to write this stuff? In recent work, in order to write a relatively complex set of plugins, you need to handle a variety of asynchronous operations. But for the sake of size and compatibility, it is not intended to introduce any pollyfill, even Babel is not allowed to use, which means that it can only be handled in ES5 way. The way to use callbacks is very bad for decoupling, so I found another way to deal with this problem. The problem is done, but also triggered some of their own thinking: the processing of JS asynchronous operation, there are some ways?
First, the callback function
The legendary "Callback Hell" is from the callback function. And the callback function is the most basic method of handling JS asynchronous operation. Let's look at a simple example:
First define three functions:
function fn1 () { console.log (' Function 1 ')}function fn2 () { setTimeout (() = { Console.log (' Function 2 ') },}function Fn3 () { Console.log (' function 3 ')}
fn2
This can be seen as an asynchronous function that is deferred for 500 milliseconds. Now I want to be able to execute in turn, fn1
fn2
fn3
. To ensure that fn3
in the final execution, we can take it as fn2
a callback function:
function fn2 (f) { setTimeout (() = { Console.log (' Function 2 ') f () }, +)}fn2 (FN3)
As can be seen, fn2
and fn3
fully coupled, if there are multiple similar functions, it is likely that fn1(fn2(fn3(fn4(...))))
this situation will occur. Back to the evils of hell I will not repeat, I believe you must have their own understanding of the reader.
Second, event Publish/Subscribe
The Publish/subscribe model is also one of many design patterns, which is exactly how you can handle asynchronous operations fairly gracefully under ES5. What is a publish/subscribe? In the example above, fn1
fn2
fn3
It can be seen as the publisher of an event, and as long as it executes, an event is published. At this point, we can subscribe to the event and process the events in bulk, including their sequencing. Here we add a method for the message subscriber based on the example in the previous section (for simplicity, the code uses the ES6 notation):
Class Asyncfunarr { constructor (... arr) { This.funcarr = [... arr] } Next () { CONST FN = This.funcar R.shift () if (typeof fn = = = ' function ') fn () } Run () { this.next () }}const Asyncfunarr = new ASYNCFU Narr (FN1, fn2, Fn3)
Then, fn1
fn2
within,, fn3
call its next()
method:
function fn1 () { console.log (' Function 1 ') asyncfunarr.next ()}function fn2 () { setTimeout (() = { C17/>console.log (' function 2 ') Asyncfunarr.next () },}function Fn3 () { Console.log (' function 3 ') asyncfunarr.next ()}//output =>//function 1//function 2//function 3
As you can see, the processing order of the functions equals AsyncFunArr
the order of the arguments passed in. To AsyncFunArr
maintain an array internally, each invocation of the next()
method will sequentially roll out an object saved by the array and execute it, which is a common method I use in my actual work.
Third, Promise
Using promise, there is no need to write a single message subscriber function, only the asynchronous function will return a promise. And look at the example:
function fn1 () { console.log (' Function 1 ')}function fn2 () { return new Promise ((Resolve, reject) + = { set Timeout (() = { Console.log (' Function 2 ') Resolve () } )})}function Fn3 () { Console.log (' Function 3 ')}
Similarly, we define three functions, which fn2
are asynchronous functions that return promise, and now we want to execute them sequentially, just as follows:
FN1 () fn2 (). then (() = {fn3 ()})//output =>//function 1//function 2//function 3
There are two major differences between the use of promise and callbacks, the first one is decoupled from each other, fn2
and the fn3
second is that the function is nested revision for chained invocation, both semantically and in a way that is more friendly to the developer.
Iv. Generator
If the use of promise can be linked to the callback, then the generator method can eliminate the large heap of promise feature methods, such as a lot of then()
.
function fn1 () { Console.log (' function 1 ')}function fn2 () { setTimeout (() = { Console.log (' function 2 ') ) Af.next () },}function Fn3 () { Console.log (' function 3 ')}function* Asyncfunarr (... fn) { fn[0] ( ) yield fn[1] () fn[2] ()}const af = Asyncfunarr (fn1, fn2, Fn3) Af.next ()//output =>//function 1//function 2// Function 3
In this example, the generator function asyncFunArr()
accepts a list of functions to be executed fn
, and the asynchronous function is yield
executed. Within an asynchronous function, by af.next()
activating the next step of the generator function.
So roughly, it looks like the Publish/subscribe pattern is very similar, all by calling a method inside an asynchronous function to tell the subscriber to do the next step. But this approach is still not elegant, for example, if there are multiple asynchronous functions, then the generator function must be rewritten, and at the level of semantics is also a bit less intuitive.
Five, elegant async/await
Using the latest version of node is natively supported async/await
, and can be used in older browsers through a variety of pollyfill. So why is it the async/await
most elegant way to say it? And look at the code:
function fn1 () { console.log (' Function 1 ')}function fn2 () { return new Promise ((Resolve, reject) + = { set Timeout (() = { Console.log (' Function 2 ') Resolve () } )})}function Fn3 () { Console.log (' Function 3 ')}async function Asyncfunarr () { fn1 () await fn2 () fn3 ()}asyncfunarr ()//Output =>// function 1//function 2//function 3
Did you find that when you define an asynchronous function, its content is exactly the same as fn2
when you used promise in the previous article? Then look at the execution function asyncFunArr()
, which is very similar in the way it executes and when you use generator.
Asynchronous operations return promise, requiring sequential execution only to await the corresponding function, which is semantically friendly and easy to maintain code-just return to promise and await it. There is no need to maintain internal execution like generator yield
.
Vi. the end of the
As an induction and summary, the content of this article is a lot of knowledge points from the experience of others, but added some of their own understanding and experience. Do not seek popular science in others, but seek to accumulate as individuals. I hope readers can put forward the revised comments and learn to progress together!
is written at the end: for Freedom look outside the world, and it this line, not to go to Google data, finally, Amway a V--PN agent. a red apricot accelerator , to Google data is the absolute first choice, fast connection, easy to use. I bought 99¥ for a year, through this link (http://my.yizhihongxing.com/aff.php?aff=2509 After registering to pay the coupon code WH80, split down, only 7 yuan per month, special benefits.
This document tags : javascript native JavaScript advantage javascript asynchronous JS Asynchronous operation callback function tensorflow REST server
Turn from SUN's BLOG-focus on Internet knowledge, share the spirit of the Internet!
Address: A talk about several ways to deal with JavaScript asynchronous Operation
Related reading : TensorFlow "machine learning": How to correctly grasp the Google Deep Learning Framework TensorFlow (second generation distributed machine learning system)? "
Related reading : TensorFlow "machine learning": understanding and implementation of fast neural style "quick stylized images"
related reading:" I am a G powder, has been concerned about Google, recently Google has some little gestures, probably a lot of people do not understand "
related reading:" machine learning leads to technological innovation in the field of cognition, so how can the SaaS industry be changed by machine learning?" "
related reading:"VPS Tutorial Series: DNSMASQ + DNSCrypt + SNI Proxy smooth access to Google configuration tutorial "
Related reading: useful for programmers: 2017 latest in Google's Hosts file download and summary of the various hosts encountered the problem of the solution and configuration of the detailed
Related reading: Aaron swartz– The internet genius of the life course: every moment asked himself, now the world what is the most important thing I can participate in doing? "
Related reading: " site environment Apache + PHP + mysql xampp, how to implement a server on the configuration of multiple sites?" "
Related reading: What is the engineer culture? Why are the engineers alive? As an IT or internet company Why should the engineer text
related reading: the Win10 perpetual activation tutorial and how can I see if the Windows system is permanently activated? 》
Related blog:SUN ' S blog -Focus on Internet knowledge and share the spirit of Internet! Go and see:www.whosmall.com
Original address: http://whosmall.com/?post=255
Talking about several methods of handling JavaScript asynchronous operation