javascript asynchronous programming in detail

  • 2020-12-26 05:33:52
  • OfStack

The problems with asynchronous programming are not apparent in client Javascript, but they become apparent in the large number of asynchronous IO operations as server-side Javascript becomes more widely used. There are many different ways to solve this problem, and this article discusses some of them without going into depth. You need to choose a method that suits you according to your own situation.

This article gives you a detailed introduction to asynchronous programming in js, as follows

1 About asynchrony of events

Events are one of the most important features of JavaScript, which is designed to be asynchronous with js 1. So let's talk about 1 event mechanism.

In an js file, if you want to run a function, there are two methods: one is a direct call, such as foo(), and the second is triggered by an event, which is also called a callback function, such as passed to the setTimeout function and the onready attribute.

1. Events in the setTimeout function are asynchronous
setTimeout is also essentially an asynchronous event that is triggered when the delay time is up, but sometimes (and most of the time) it will not execute at a given delay time, as shown in the code below


  var start = new Date();
  setTimeout(function() {
   console.log('settimeout1:',new Date()-start);
  }, 500);
  while (new Date() - start < 1000) {
   console.log('in while');
  }
  document.getElementById('test').addEventListener('click', function(){
   console.log('test:',new Date()-start);
  }, false)
  for(var i=0;i<10000;i++){
   console.log('in for');
  }
  setTimeout(function(){
   console.log('settimeout2: ',new Date()-start);
  },1000);
  /* 10214
  in while
  index.jsp ( The first  19  line )
  10000
  in for
  index.jsp ( The first  25  line )
  settimeout1: 2263
  index.jsp ( The first  16  line )
  settimeout2: 3239
  index.jsp ( The first  28  line )
  test: 10006
  index.jsp ( The first  22  line )
  test: 28175
  index.jsp ( The first  22  line )
  test: 28791
  index.jsp ( The first  22  line )
  test: 28966
  index.jsp ( The first  22  line ) */

If the normal understanding is that the delay function should break the while loop after 500 milliseconds, which it does not, and I did not print test immediately when I clicked on div between the while loop and the for loop, the explanation is this:

a) event queue. Call setTimeout function, can add to it the callback function to the event queue (event has been initialized and in memory), and then continue to execute that code, until there is no code can run (no normal operation flow, including the content of the asynchronous event functions), from the event queue pop inside out a suitable to run the event.

js) js is single-threaded, and the event handler does not run until the thread is idle.

2 The asynchrity of normal events is similar to setTimeout
2 promise object and deferred object

1. promise
promise is a solution to the problem of asynchronous programming callbacks such as ajax being too nested to make the code difficult to understand, especially in nodejs, where asynchronism is ubiquitous. Different frameworks for the implementation of promise, promise in jquery API under 1.

The principles of promise are not explained here, but are described in another section.

Traditional ajax asynchronous programming is written like this (before jquery1.5) :


$.get('url', function(){
 $.get('url1', function(){
  $.get('url2', function(){

  }, 'json');
 }, 'json');
}, 'json');

Writing code in this way makes development and maintenance extremely difficult. Fortunately, promise was introduced after jquery1.5, and it can be written as follows:


 $.ajax( "example.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });

Now it looks a lot easier.

2. deferred object


var nanowrimoing = $.Deferred();
var wordGoal = 5000;
nanowrimoing.progress(function(wordCount) {
var percentComplete = Math.floor(wordCount / wordGoal * 100);
$('#indicator').text(percentComplete + '% complete');
});
nanowrimoing.done(function(){
$('#indicator').text('Good job!');
});

3.worker objects and multithreading

4. Asynchronous script loading

1. The location of traditional scripts on the page
Scripts fall into two broad categories: blocking and non-blocking. Blocking here means load blocking rather than run blocking.


<!DOCTYPE html>
<html>
<head>
<script src="headScript"></script>
<script defer src="deferredScript"></script>
</head>
<body>
 <script async defer src="chatWidget"></script>
 <script async defer src="asyncScript"></script>
</body>
</html>

This part of the code above is a standard about the positions of the script in a page, 1. The traditional headScript without any mask is blocking type script, because the browser interpretive execution JavaScript from top to bottom, so this part of the script file will be executed, the start of the 1 and is prior to the execution of the DOM will not render, but head label inside css loads. 2. Scripts with the defer attribute are loaded at the same time as DOM is rendered, but they are executed after DOM is rendered. Unfortunately, not all browsers support the defer attribute, hence the jquery(function) thing. 3. With both async and defer attributes, defer overrides async, but with async alone, the script loads and runs at DOM render time.

2. Programmable script loading
If, instead of introducing js files on the page at the beginning of 1, the js script is dynamically loaded through user interaction, it can be added programmatically.

There are two ways for the browser to get the server script, ajax to get and execute it through the eval function, and DOM to insert the other one < script > Tags are usually used the second way because the browser helps us generate HTTP requests and eval leaks scope.


var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = '/js/feature.js';
head.appendChild(script);
script.onload = function() {
//  Now you can call the functions defined in the script 
}

That's the end of this article, and hopefully it will help you learn about js asynchronous programming.


Related articles: