In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
What are the knowledge points of this article "what are the ways of JavaScript asynchronous processing?" most people do not understand, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what are the ways of JavaScript asynchronous processing?"
There are two asynchronous processing methods in JavaScript: 1, use "Promise" to handle asynchrony, which can help manage the code returned asynchronously; 2, use "async/await" to handle async, and handle async events with synchronous syntax.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
Asynchronous processing of JavaScript
Promise
(1) promise object is a specification and a pattern proposed by commonJS working group, which aims to provide a unified interface for asynchronous programming.
(2) promise is a mode, and promise can help manage the code returned asynchronously. He talks about code encapsulation and adding a management layer similar to event handling. We can use promise to register the code, which will run after the promise succeeds or fails.
(3) after the promise is completed, the corresponding code will also be executed. We can register any number of functions and run them after success or failure, or we can register event handlers at any time.
(4) promise has two states: 1, waiting (pending); 2, completion (settled).
Promise waits until the asynchronous call it wraps returns / times out / ends.
(5) at this time, the promise status becomes complete. Completion status is divided into two categories: 1, resolution (resolved); 2, rejection (rejected).
(6) promise solution (resolved): means a smooth end. Promise rejection (rejected) means that it did not end smoothly.
/ / promisevar p=new Promise (function (resolved)) / / deal with it here. Maybe you can use ajaxsetTimeout (function () {var result=10*5; if (result===50) {resolve (50);} else {reject (new Error ('Bad Math'));}}, 1000);}); p.then (function (result) {console.log (' Resolve with a values of% dazzling);}); p.catch (function () {console.error ('Something went wrong');})
(1) the key to the code is the call to setTimeout ().
(2) importantly, he called the functions resolve () and reject (). The resolve () function tells the promise user that the promise has been resolved; the reject () function tells the promise user that the promise did not complete successfully.
(3) others use promise code. Note the use of then and catch, which can be thought of as handlers for onsucess and onfailure events.
(4) the ingenious thing is that we separate promise processing from state. That is, we can call p.then (or p.catch) as many times as we like, regardless of the state of the promise.
(5) promise is the standard way for ECMAscript 6 to manage asynchronous code, and the javascript library uses promise to manage ajax, animation, and other typical asynchronous interactions.
In a nutshell, the idea is that each asynchronous task returns a promise object that has a then method that allows you to specify a callback function. For example, the callback function f2 of F1 can be written as:
F1.then (f2)
F1 needs to be rewritten as follows (using the implementation of jquery):
Function F1 () {var dfd=$.deferred (); settimeout (function () {/ / F1 task code dfd.resolve ();}, 500); return dfd.promise;}
The advantages of writing like this: the callback function is written in a chain, the flow of the program can be seen clearly, and there is a set of supporting methods that can achieve a lot of powerful functions.
For example, specify multiple callback functions
F1 (). Then (f2). Then (f3)
For example, specify the callback function when an error occurs:
F1 (). Then (f2). Fail (f3)
Moreover, it has an advantage that none of the previous three methods have: if a task has been completed and a callback function is added, the callback function will be executed immediately.
So you don't have to worry about missing an event or signal.
The disadvantage of this approach is that it is relatively difficult to write and understand.
Async await
Since the advent of ES6 Promise, asynchronous code has gradually changed from callback hell to elegant functional pipeline processing, but for unfamiliar developers, it has only changed from callback hell to Promise hell.
The new async/await is standardized in ES8. Although it is just a syntax candy for the combination of Promise and Generator Function, asynchronous events can be handled with synchronous syntax through async/await, just as if the old tree is blooming new flowers, and the writing style is completely different from that of Promise:
Function wait (time, fn) {return new Promise (resolve = > {setTimeout () = > {console.log ('wait:', time) resolve (fn?) Fn (): time)}, time)})} await wait (500,500, () = > console.log ('bar')) console.log (' foo') / / wait: 500max / bar// foo
By wrapping setTimeout as Promise and calling it with the await keyword, you can see that the result will be synchronous execution, first bar, then foo, that is, writing asynchronous events as synchronous processing as mentioned at the beginning.
Look at another example:
Async function withAsyncAwait () {for (let I = 0; I)
< 5; i++) { await wait(i*500, () =>Console.log (I)}} await withAsyncAwait () / / wait: 0 / 0 / wait: 500 / 1 / wait: 1000 / 2 / wait: 1500 / 3 / wait: 2000 / 4
The withAsyncAwait function is implemented in the code, and the wait function is executed repeatedly with the for loop and the await keyword; when executed here, the loop waits for a different number of seconds each time in order to execute the next loop.
When using async/await, since the await keyword can only be executed in async function, be sure to use it at the same time.
In addition, when handling asynchronous events with loops, it should be noted that many Array methods provided after ES6 do not support async/await syntax. If forEach is used instead of for here, the result will be synchronous execution, and numbers will be printed every half a second:
The above is about the content of this article on "what are the ways of JavaScript asynchronous processing". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.