JavaScript Asynchronous Programming

Source: Internet
Author: User
Tags readfile setinterval

1. Preface

Usually development often use JS asynchronous programming, because the front-end display page is based on the network set-top box (IPTV general performance is not very good, Ott better), the company mainly to take the way of asynchronous programming has settimeout, SetInterval, Requestanimationframe, Ajax, why the use of asynchronous, take the business, if the front-end all to take a synchronous way, that load pictures, generate DOM, network data requests will greatly increase the length of the page rendering.

2.JS operating mechanism

JS is a single-threaded operation, which means that two of pieces of code cannot run at the same time, but must be run incrementally, so asynchronous code is not executed during synchronous code execution. Asynchronous code is added to the event queue only after the synchronization code has finished executing.

This involves the execution stack and the task queue:

Synchronization code is stored in the execution stack, followed by the LIFO principle;

Asynchronous code in the task queue, task queue and macro tasks and micro-tasks (micro-task execution priority higher than the macro task), followed the FIFO principle;

Take a look at the order in which the code is executed (think about whether it is consistent with the correct output order first)

1 functionfoo () {2Console.log (' Start ... ');3 return bar ();4 }5 functionBar () {6Console.log (' Bar ... '));7 }8 //this uses ES6 's arrow function, Promise function9 varPromise =NewPromise (function(resolve,reject) {TenConsole.log (' Promise ... '); One resolve (); A }); -Promise.then (() =>console.log (' Promise resolve ... ')); -SetTimeout (() =>console.log (' timeout ... '), 0); the foo () -Console.log (' End ... ');

Please look at the answer

Promise ...
Start ...
Bar ...
End ...
Promise Resolve ...
Timeout ...

Here to analyze (let's not tangle with the task queue, I explained the asynchronous micro-task, asynchronous macro task is no basis, understand, do not delve into):

The program officially started execution is starting from 9 lines of initializing the Promise object, first printing promise ...

Then the discovery is Promise.then callback function, this is an asynchronous micro-task, put into the task queue, waiting for the synchronization task to execute

Further down is the timeout timer, which is an asynchronous macro task that is also placed in the task queue, waiting for the synchronization task to execute and the asynchronous micro task to execute

Then down is the Foo method, this is the synchronization task, borrowed the network popular sentence "JavaScript function is a class citizen", print log start ... After the callback execution bar method, there will be two execution stack (put Foo, bar into the stack, bar after the execution of the pop-up stack, foo in turn)

See MDN for concurrency model and event Loop (Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/EventLoop)

3. Asynchronous Programming

In the way of asynchronous programming, commonly used timers, Ajax, Promise, Generator, async/await, details are as follows:

3.1. Timer 3.1.1.setTimeout and SetInterval

Here, take settimeout for example.

A simple clock

1(function(){2             vardiv = document.createelement (' div '), timer;3 Document.body.appendChild (div);4             //synchronous code, 5s after executing asynchronous code block display Clock5             //dosomething ()6SetTimeout (function(){7 EXECFN (); 8},5000);9             functionTimechange (callback) {Tendiv.innerhtml = ' Current time: ' +GetCurrentTime ();  One                 if(NewDate (). getseconds ()%5 = = = 0){ A                     //the current number of seconds is a multiple of 5 off timer - cleartimeout (timer); -                     //dosomething ... the Console.log (timer); -Timer = SetTimeout (execfn,100); -}Else{ - cleartimeout (timer); + EXECFN (); -                 } +             } A             functionEXECFN () { atTimer1 = Window.settimeout (timechange,1000); -             } -             functionGetCurrentTime () { -                 varD =NewDate (); -                 returnD.getfullyear () + '-' + (D.getmonth () +1) + '-' +d.getdate () + ' +d.gethours () + ': ' +d.getminutes () + ': ' +d.getseconds () + ' Week ' +Getweek (); -             } in             functionGetweek () { -                 varD =NewDate (); to                 varWeek; +                 Switch(D.getday ()) { -                      Case(4): week= ' four '; Break; the                     //omitted *                     default: week= ' * '; Break; $                 }Panax Notoginseng                 returnWeek; -             } the})();

Normal logic code must be much more complex, but the logic of writing asynchronous code with Settimeou is roughly the same.

Look at the following example

If you have questions, why not first output 2 and then output 1

SetTimeout and SetInterval are performed at a 4~5ms time interval

See SetInterval code below

The count count output is 252, so the execution interval is approximately 4ms

3.1.2.requestAnimationFrame

Look at the Caniuser support situation.

Look at this trend in addition to opera other browsers support the Requestanimationframe method

In peacetime business also see company colleagues encapsulated Requestanimationframe method. If you encounter some version of the browser does not support this method, you need to rewrite, Requestanimationframe is actually similar to the principle of anti-shake throttle implementation, see the code

1 varVendors = [' WebKit ', ' Moz '];2  for(vari = 0; I < vendors.length &&!window.requestanimationframe; ++i) {3     varVP =Vendors[i];4Window.requestanimationframe = window[vp+ ' Requestanimationframe '];5 }6 if(!window.requestanimationframe) {7     varLasttime = 0;8Window.requestanimationframe =function(callback) {9         varnow =NewDate (). GetTime ();Ten         varNexttime = Math.max (Lasttime + +, now);//Browser rendering time interval of approximately 16ms One         returnWindow.settimeout (function(){ ALasttime =Nexttime; - callback (); -},nexttime-Now ); the     }; -}

Interested students can see the masterpiece of this great God

Https://codepen.io/caryforchristine/pen/oMQMQz

3.2.Ajax

Look directly at a simple Ajax asynchronous processing code

1(function(){2             varxmlhttp = window. XMLHttpRequest?NewXMLHttpRequest ():NewActiveXObject ("Microsoft.XMLHTTP");3             varurl = "Authorinfo.json";4Xmlhttp.onreadystatechange =function(){5                 if(xmlhttp.readystate==4){6                     if(xmlhttp.status==200){7 Console.log (xmlhttp.response);8                         //get data asynchronously and then dosomething9                     }Ten                 } One             } AXmlhttp.open (' GET ', url,true); -Xmlhttp.send (NULL); -})();

Chrome Print Log

3.3.Promise

Promise is a solution for asynchronous programming that is more logical and powerful than traditional solutions-callback functions and events. It was first proposed and implemented by the community, ES6 wrote it into the language standard, unified the usage, the native provided the Promise object

Simple reading of File instances

1 varFS = require (' FS ')2 varRead =function(filename) {3     varPromise =NewPromise (function(Resolve, reject) {4Fs.readfile (filename, ' UTF8 ',function(err, data) {5             if(err) {6 reject (err);7             }8 resolve (data);9         })Ten     }); One     returnpromise; A } -Read (' Authorinfo.json ') -. Then (function(data) { the console.log (data); -     returnRead (' Not_exist_file '); - }) -. Then (function(data) { + console.log (data); - }) +.Catch(function(err) { AConsole.log ("Error Caught:" +err); at }) -. Then (function(data) { -Console.log ("Completed"); -})

Using node to run the result is as follows:

The promise constructor takes a function as a parameter, and the two parameters of the function are resolve and reject (function)

When the state is changed from pending to Resolved execution resolve (), the rejected executes reject (), and when the promise instance is generated, the callback can be specified with then

Then (function success () {},function fail () {}), this method returns a new Promise object, so you can make a chained call

For promise including the following generator please see Ruan Teacher's Blog

3.4.Generator

I felt very magical when I first contacted generator, after all, I never thought that the function would break the breakpoint (under the description is inaccurate, do not spray), that is to say, part of the function can stop to process additional blocks of code, and then go back to the pause to continue execution.

Executing the Generator function returns a Walker object, that is, the Generator function, in addition to the state machine, is a Walker object generation function. Returns the iterator object that iterates through each state within the Generator function.

This shows that generator returns a Walker object that can be traversed with a for (ES6 new attribute, mainly for objects with symbol.iterator properties, including arrays, Set,map, class arrays, and so on).

Generator syntax function* name () {}, there is a space between the general * and the function name, which can be decorated with the yield keyword, it is important to note that the expression after yield is executed only when the next method is called and the internal pointer points to the statement. Do you think that generator to manually execute the next method is too much trouble, and then introduce the current JS to async the ultimate solution

3.5. async/await

Async and await are the new syntax in ES 7, which is not supported in the new to even ES 6.

Can take advantage of Babel conversion

Online conversion Address: https://babeljs.io/, you can also install BABEL-CLI for conversion

1Const FS = require (' FS ');2Const UTILS = require (' Util ');3Const READFILE =utils.promisify (fs.readfile);4AsyncfunctionReadjsonfile () {5     Try {6Const FILE1 = await readFile (' Zh_cn.json ');7Const FILE2 = await readFile (' Authorinfo.json ');8 Console.log (file1.tostring (), file2.tostring ());9}Catch(e) {TenConsole.log (' wrong '); One     } A  - } -Readjsonfile ();

You can see that asynchronously reads two files sequentially, and if you take advantage of generator, you need to perform next,async/await manually to automate

Write poorly or have the wrong place to welcome the great God in time to point out.

Welcome to Error Correction ~

 

JavaScript Asynchronous Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.