Previously encountered in the project many times because the async-induced variables have no value, so aware of the importance of understanding the synchronization and asynchronous mechanism in JS
In single-threaded JS, the async code is placed in an event queue until all other code executes, without blocking the thread.
Here are some of the most common asynchronous scenarios for JS:
- Asynchronous functions SetTimeout and SetInterval
Asynchronous functions, such as settimeout and setinterval, are pressed into the queue called the event loop.
SetTimeout: After the specified number of milliseconds, the functions processed by the timer task are added to the end of the queue for execution. So sometimes you can use settimeout to solve problems with async.
SetInterval: Adds a timer task handler to the end of the queue at the specified period (in milliseconds).
The Event loop is a callback function queue. When an asynchronous function executes, the callback function is pressed into the queue. The JavaScript engine does not begin processing the event loop until the asynchronous function finishes. This means that the JavaScript code is not multi-threaded, even if it behaves similarly. The event loop is a first in, in, Out (FIFO) queue, which indicates that callbacks are executed in the order in which they are queued.
- Ajax
- Many of the functions in node. JS are also asynchronous
Solve the problem caused by the JS async method:
- Named functions
A convenient solution to clear nested callbacks is to avoid nesting more than two layers. Pass a named function as a callback parameter instead of passing an anonymous function
Example: 1 varfromlatlng, tolatlng;2 varRoutedone =function(e) {3Console.log ("Annnnd FINALLY here ' s the directions ..." );4 //Do something with e5 };6 varToaddressdone =function(results, status) {7 if(Status = = "OK" ) {8TOLATLNG = Results[0].geometry.location;9 map.getroutes ({Ten Origin: [Fromlatlng.lat (), FROMLATLNG.LNG ()], One destination: [Tolatlng.lat (), TOLATLNG.LNG ()], ATravelmode: "Driving", -Unitsystem: "Imperial", - Callback:routedone the }); - } - }; - varFromaddressdone =function(results, status) { + if(Status = = "OK" ) { -FROMLATLNG = Results[0].geometry.location; + Gmaps.geocode ({ A address:toaddress, at Callback:toaddressdone - }); - } - }; - Gmaps.geocode ({ - address:fromaddress, in Callback:fromaddressdone -});
The Async.js library can help us deal with multiple Ajax requests/responses, such as:
1 Async.Parallel ([2 function(done) {3 Gmaps.geocode ({4 address:toaddress,5Callbackfunction(Result) {6DoneNULL, result);7 }8 });9 },Ten function(done) { One Gmaps.geocode ({ A address:fromaddress, -Callbackfunction(Result) { -DoneNULL, result); the } - }); - } -],function(errors, results) { +Getroute (Results[0], results[1] ); -});
- Using Promise
Promise in the process of executing asynchronously, the code that executes the code and the result is clearly separated:
Promise can also do a number of asynchronous tasks, for example: There is an asynchronous task, you need to do task 1, if the task succeeds and then do Task 2, any task failure will not continue and execute the error handler function.
job1.then(job2).then(job3).catch(handleError); //job1
、job2
和job3
都是Promise对象
Cases:
1' Use strict ';2 3 varlogging = document.getElementById (' Test-promise2-log '));4 while(Logging.children.length > 1) {5Logging.removechild (logging.children[logging.children.length-1]);6 }7 8 functionlog (s) {9 varp = document.createelement (' P ');Tenp.innerhtml =s; One Logging.appendchild (p); A } - //returns the calculated result of Input*input after 0.5 seconds: - functionMultiply (input) { the return NewPromise (function(Resolve, reject) { -Log (' calculating ' + input + ' x ' + input + ' ... ')); -SetTimeout (Resolve, $, input *input); - }); + } - + //returns the calculated result of Input+input after 0.5 seconds: A functionAdd (Input) { at return NewPromise (function(Resolve, reject) { -Log (' calculating ' + input + ' + ' + ' + input + ' ... ')); -SetTimeout (Resolve, +, input +input); - }); - } - in varp =NewPromise (function(Resolve, reject) { -Log (' Start new Promise ... '); toResolve (123); + }); - the p.then (multiply) * . Then (add) $ . Then (multiply)Panax Notoginseng . Then (add) -. Then (function(Result) { theLog (' Got value: ' +result); +});
Two ways to Promise
1 varP1 =NewPromise (function(Resolve, reject) {2SetTimeout (Resolve, $, ' P1 '));3 });4 varP2 =NewPromise (function(Resolve, reject) {5SetTimeout (Resolve, "P2");6 });7 //execute P1 and P2 at the same time, and then execute when they are complete:8Promise.all ([P1, p2]). Then (function(results) {9Console.log (results);//get an array: [' P1 ', ' P2 ']Ten});
1 varP1 =NewPromise (function(Resolve, reject) {2SetTimeout (Resolve, $, ' P1 '));3 });4 varP2 =NewPromise (function(Resolve, reject) {5SetTimeout (Resolve, "P2");6 });7Promise.race ([P1, p2]). Then (function(Result) {8Console.log (result);//' P1 '9});
Becausep1
Execute faster, Promisethen()
Will get results‘P1‘
。p2
Continues to execute, but the execution results are discarded.
This article refers to:
http://blog.csdn.net/u013063153/article/details/52457307
Https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/ 0014345008539155e93fc16046d4bb7854943814c4f9dc2000
Asynchronous and synchronous in JS to solve problems caused by asynchronous