In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what are the ways to deal with asynchronous events". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Synchronized? Asynchronous?
First of all, of course, you have to understand what synchronous and asynchronous mean, respectively.
These two nouns are always confusing for beginners. After all, the literal meaning in Chinese is easy to be understood in reverse. From the perspective of information science, [https:// developer.mozilla.org/en-US/docs/Glossary/Synchronous] refers to doing things one by one, while asynchronism refers to the parallel processing of many things together.
For example, when we go to the bank to do business, the queue in front of the window is synchronous execution, and the one who gets the number to do something else is asynchronous execution. Through the characteristics of Event Loop, asynchronous events can be said to be easy in JavaScript.
So what is the way to handle asynchronous events in JavaScript?
Callback function
What we are most familiar with is the callback function. For example, event listeners registered when a web page interacts with users need to receive a callback function; or other functions of Web API, such as setTimeout and xhr, can also be triggered by passing callback functions at the time required by users. Let's take a look at an example of setTimeout:
/ / callback function withCallback () {console.log ('start') setTimeout () = > {console.log (' callback func')}, 1000) console.log ('done')} withCallback () / / start / / done / / callback func
After the setTimeout is executed, after the specified interval, the callback function is placed at the end of the queue and waits for the event loop to process it.
Note: because of this mechanism, the time interval set by developers to setTimeout is not exactly equal to the elapsed time from execution to trigger, so you should pay special attention when using it!
Although callback functions are very common in development, there are many unavoidable problems. For example, because functions need to be passed to other functions, it is difficult for developers to control the processing logic in other functions, and because callback functions can only cooperate with try. Catch catches errors and is difficult to control when asynchronous errors occur; there is also the most famous "callback hell".
Promise
Fortunately, Promise appeared after ES6, saving developers from hell. Its basic usage is also very simple:
Function withPromise () {return new Promise (resolve = > {console.log ('promise func') resolve ()})} withPromise (). Then () = > console.log (' then 1'). Then () = > console.log ('then 2') / / promise func / / then 1 / / then 2
What was not mentioned in the previous discussion of Event Loop is that in the Web API standard of HTML 5, Event Loop adds a micro-task queue (micro task queue), and Promise drives it through the micro-task queue; the trigger time of the micro-task queue is when the stack is emptied, the JavaScript engine will first confirm whether there is anything in the micro-task queue, and if so, it will be executed first, and the new task will not be taken out from the queue to the stack until it is cleared.
As in the example above, when the function returns a Promise, the JavaScript engine puts the later function into the micro-task queue, loops over and over again, and outputs the results listed above. The subsequent .then grammar sends back a new Promise, and the parameter function receives the result of the previous Promise.resolve, which allows the developer to handle asynchronous events in a pipe-like manner.
If you add setTimeout to the example, you can better understand the difference between micro-tasks and general tasks:
Function withPromise () {return new Promise (resolve = > {console.log ('promise func') resolve ()})} withPromise (). Then () = > console.log (' then 1')). Then () = > setTimeout (() = > console.log ('setTimeout'), 0)). Then () = > console.log (' then 2')) / / promise func / / then 1 / then 2-> Micro task priority execution / / setTimeout
In addition, asynchronous errors that are difficult to handle by callback functions mentioned earlier can also be caught through .catch syntax.
Function withPromise () {return new Promise (resolve = > {console.log ('promise func') resolve ()})} withPromise () .then () = > console.log (' then 1')) .then () = > {throw new Error ('error')}) .then (() = > console.log (' then 2')) .catch ((err) = > console.log ('catch:') Err) / / promise func / / then 1 / / catch: error / /... error call stack
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, () = > console.log ('bar')) console.log (' foo') / / wait: 500 / / 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: 1000 / / 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 using loops to handle asynchronous events, it is important to note that many Array methods provided after ES6 do not support async/await syntax. If you replace for with forEach, the result will be synchronous execution, printing numbers every half a second.
This is the end of the content of "what are the ways to handle asynchronous events". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.