In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you about Javascript asynchronous programming, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
This may be a deeper topic. What is async?
Generally speaking, async is deferred execution in javascript. Strictly speaking, the asynchronous programming capabilities in javascript are provided by BOM and DOM, such as setTimeout,XMLHttpRequest, DOM's event mechanism, HTML5's newly added webwork, postMessage, and so on. All these things have a common feature, that is, they have a callback function that implements control inversion. Since reversal of control is a more esoteric problem, I don't want to expand it here. To be sure, however, the existence of callback functions interrupts the original execution process, leaving them to appear and execute at the right time, which is a very convenient mode. Compared with active polling, you can see how energy-efficient it is. In synchronous programming, the code is basically executed from top to bottom, while in asynchronous programming, some code is written into the callback function. If there is a dependency between the code, the callback function nesting the callback function is also rare. This nesting structure is hell for future maintenance. Another situation we have to face is that try...catch cannot catch the exception that occurs a few milliseconds later. In addition, in addition to setTimeout, asynchronous programming is basically undertaken by the event mechanism, and when their callback functions occur is basically unknown. They may be unable to respond because of system-level errors in the background, or the system is too busy to respond for a moment. In both cases, we must also provide a strategy to interrupt the operation, that is, the so-called abort. These are the topics to be dealt with in asynchronous programming.
$.post ("/ foo.json", function (dataOfFoo) {/ / Ajax callback of multi-layer nested structure $.post ("/ bar.json", function (dataOfBar) {$.post ("/ baz.json", function (dataOfBaz) {alert ([dataOfFoo, dataOfBar, dataOfBaz]);});}); function throwError () {throw new Error ('ERROR');} try {setTimeout (throwError, 3000) } catch (e) {alert (e); / / the exception here cannot be caught}
As you encounter such requirements all the time in javascript programming, the implementation of relevant lightweight API is a top priority. As mentioned above, it only needs the following functions, which can store a set of callback functions (domReary, multi-cast events, special effects), execute all callback functions at a specific time, trigger the corresponding handler function (negative callback) if an error occurs, abort the whole operation, start again from the break, and if more is required, we want to be able to switch from serial to parallel, from parallel to serial. There may be many concepts that you don't understand, are there? But to get good special effects, these are necessary. If you have played the back-end JS, you must have heard of node.js, and now it is basically synonymous with it. Routing dispatch, IO operation, are asynchronous, event-driven, in order to achieve elegant asynchronous programming, Daniel is very busy, one by one has been proposed, such as do.js. Step.js, async.js, flow.js. It is either too chicken rib or can not be applied to the front end. So we need a solution that is suitable for the front end.
One thing we must understand is that what you think of has already been studied and a solution has been given. One of the top ten javascript frameworks, Mochikit, got Deferred from Python's Twisted library, and then learned it for dojo, and now you can see that the same thing is on jQuery1.5 again. However, Mochikit's Deferred also has an unknown branch, created by Japanese Daniel cho45 (he also works on BigInt, cross-browser Testing, famous after amachang, uupaa, edvakf, nanto), called JSDeferred. First of all, the Deferred of the dojo faction (including jQuery) has been in an invincible state, working out a set of norms with Common.js. All promises,then,when was formulated at that time, and jQuer basically accepted it completely. Another branch, cho45 JSDeferred, the idea is very strange, do not use arrays to load callback functions, but through setTimeout,image.onload, postMessage and other asynchronous mechanisms to skillfully maintain the queue of work back to the browser itself, although it has fatal defects, but its ease of use is also approved by the Japanese JS community, my Deferred object has basically developed from it. Deferred things, I usually call asynchronous queuing, because they do require two sets of callback queuing, very vivid.
Before we move out of the asynchronous queue, let's take a look at how ordinary queues achieve delays.
Var Queue = function () {this.list = []} Queue.prototype = {constructor:Queue, queue:function (fn) {this.list.push (fn) return this;}, dequeue:function () {var fn = this.list.shift () | | function () {}; fn.call (this)}}
Call it like this:
Var Q = new Queue; q.queue (function () {log (1)}) .queue (function () {log (2)}) .queue (function () {log (3)}); while (q.list.length) {q.dequeune ();}
But this is synchronous. To be asynchronous, we need to use setTimeout:
Var el = document.getElementById ("test"); var Q = new Queue (); q.queue (function () {var self = this; el [XSS _ clean] = 1 setTimeout (function () {self.dequeue ()}, 1000);}) .queue (function () {var self = this; el [XSS _ clean] = 2 setTimeout (function () {self.dequeue ()}, 1000);}) .queue (function () {var self = this) El [XSS _ clean] = 3 setTimeout (function () {self.dequeue ()}, 1000);}) .dequeue ()
As you can see, it is absolutely unfriendly to write like this. We need to integrate setTimeout into the Queue class and make some changes to queue. Don't just pop up a function for execution. Usually, we will operate on all callbacks in the queue, such as domReay, multi-cast events.
Var Queue = function () {this.list = []} Queue.prototype = {constructor:Queue, queue:function (fn) {this.list.push (fn) return this;}, wait:function (ms) {this.list.push (ms) return this;}, dequeue:function () {var self = this, list = self.list; var el = list.shift () | function () {} If (typeof el = = "number") {setTimeout (function () {self.dequeue ();}, el);} else if (typeof el = = "function") {el.call (this) if (list.length) self.dequeue ();}
Great, if we were free to control the interval between each callback, it would be very easy to animate. But this Queue class is still a far cry from the goal we initially set. Ajax, multi-throw events, domReay will all be under its command, so it needs to use some more applicable API. People who have used dojo also know that its Deferred, like the chromosomes of DNA, is double-stranded and can catch anomalies that are not on the same timeline, and these queues cannot be discarded after one use of sanitary chopsticks, so it is impossible to support the realization of multi-throw events. To achieve these functions, you need a very complex thing, and I will solemnly introduce my asynchronous queue in the second part to see how it solves these problems gracefully.
This is what Javascript asynchronous programming is like, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow 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: 229
*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.