An in depth understanding of asynchronous problems in js interview questions

  • 2021-08-28 07:13:15
  • OfStack

Macro Tasks and Micro Tasks in js

During the interview, the basic interviewer will ask you some questions about promise, and promise is a new content of es6, which is mainly used to optimize asynchronous questions. In the written test, you are often asked to write the execution results of promise and setTimeout, so you must know the concepts of macro tasks and micro tasks!

Why use promise

If you have experienced previous jquery development projects, you will encounter the following problems: callback hell


$.ajax({
	...
	success: function() {
		...
		$.ajax({
			...
			success: function() {
				
			}
		})
		...
	}
})

Cause analysis:

ajax requests are nested, because the parameters that my second request depends on are in the results of the first request, so I have to nested them straight. ajax is asynchronous, and I can't get the results inside from outside. The problem caused by this kind of code is that it is difficult to debug, and the coupling is very high. It is a headache to change one place in the later period! Maintenance is very difficult and code readability is poor.

Therefore, promise is introduced to optimize ajax. axios is a request encapsulation library based on promise, and their bottom layer is based on js native XMLHTTPREQUEST.

promise (). then (). catch () chain call, multiple requests can be promise (). then (). then ().

What are macro tasks and micro tasks?

When thinking about this problem, you must know that javascript is a single-threaded scripting language, that is, its code can only be executed from top to bottom, and it can only do one thing at a time. Asynchrony is realized through callback function. Why not design js as a multithreaded language? The purpose of the language determines its characteristics. js was originally used for form validation and regular judgment, and for manipulating DOM elements. If js has multiple threads, one performs DOM element modification and the other performs deletion, then the browser is directly forced. What should I do? ? ? So the purpose of the language determines its characteristics, but the browser is multithreaded, and there are other threads besides the main thread.

When the js main program executes, First, run the synchronization code on the main program, put it into the macro queue when encountering setTimeout or setInterval, and put it into the micro queue when encountering the callback of promise. The program executes the main program code first, then the nextTick code, then the micro task, finally the macro task and the task queue are queued in turn, async and await are used together, and await is followed by an promise object. Let's take a look at the following code:


 setTimeout(function(){console.log(1)},0); //  Enter the macro task queue, and finally execute the macro task 
 new Promise(function(resolve,reject){
   console.log(2); // This code is in the promise Constructor, executing synchronously 
   resolve(); //  Executed resolve Then put the task into the micro queue 
 }).then(function(){console.log(3)
 }).then(function(){console.log(4)});
 process.nextTick(function(){console.log(5)});
 console.log(6); //  Main program code 
 //  Output 2,6,5,3,4,1
 
//  The following advanced code 
setTimeout(function(){console.log(1)},0); //  Enter macro tasks sorted as 1
new Promise(function(resolve,reject){
   console.log(2);
   // promise Finish execution in resolve() Will be executed then(), And here's resolve In the macro task, after executing the main program code, you must first execute the program that entered the macro queue first 
   setTimeout(function(){resolve()},0) //  Enter macro tasks sorted as 2
 }).then(function(){console.log(3)
 }).then(function(){console.log(4)});
 process.nextTick(function(){console.log(5)});
 console.log(6);
 //  Output is  2 6 5 1 3 4

Look again at the execution sequence in async and await

The code is as follows (example):


async function async1() {
  console.log(1); 
  await async2();
  console.log(2); // We have to wait here await It will be executed only after successful execution, enter micro-tasks, and sort 1
}
async function async2() {
  console.log(3);
}
console.log(4); // Main program code 
setTimeout(function() {
  console.log(5);
}, 0) // Enter the macro task and finally execute 
async1();
new Promise(function(resolve) {
  console.log(6); //  This sentence is executed synchronously 
  resolve(); 
}).then(function() {
  console.log(7); // Enter micro-tasks and sort them 2
});
console.log(8); //  Main program code 
//  Output is  4,1,3,6,8,2,7,5

Summarize

js is a single-threaded language, and its use determines its characteristics. Asynchronous operation executes synchronous code first, then micro-task, finally macro task, and the tasks in the two task queues are queued to execute in turn. The code following await must wait for promise to return the result before executing the following code, which is syntax sugar for the generator function.


Related articles: