Asynchronous questions in js interview questions

Macro task and micro task in js

During the interview, the basic interviewer will ask you some questions about promises. Promises are new content of es6 and are mainly used to optimize asynchronous problems. In the written test, you will often be asked to write about 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. The reason is that the parameters that my second request relies on are in the result of the first request, so I have to nest it all the time. Ajax is asynchronous and cannot get the result inside. 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 a place later! Maintenance is very difficult, and the code is poorly readable.
So I introduced promise to optimize Ajax. Axios is a request encapsulation library based on promise. Their bottom layer is based on js native XMLHTTPREQUEST.
Promise().then().catch() chain call, multiple requests You can promise().then().then().


What is a macro task and what is a micro task?

When thinking about this problem, you must know that javascript is a single-threaded scripting language, that is, its code can only be executed sequentially from top to bottom, and can only do one thing at a time. Asynchrony is achieved through callback functions. Why not design js as a multi-threaded 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 executes DOM element modification and the other executes deletion, then the browser is stunned, what should I do? ? ? So the purpose of the language determines its characteristics, but the browser is multi-threaded, and there are other threads besides the main thread.

When the js main program is executed, the synchronization code on the main program is run first, and when setTimeout or setInterval is encountered, it is placed in the macro queue, and when the promise callback is encountered, it is placed in the micro queue. The program executes the main program first. Code, then execute nextTick code, then micro task, finally macro task, the task queue is queued for execution in turn, async and await are used together, await is followed by a promise object, let’s take a look at the following code:

 setTimeout(function(){
    
    console.log(1)},0);  // 进入宏任务队列,最后执行宏任务
 new Promise(function(resolve,reject){
    
    
     console.log(2); //这句代码在promise构造器,同步执行
     resolve(); // 执行了resolve再把任务放入微队列
 }).then(function(){
    
    console.log(3)
 }).then(function(){
    
    console.log(4)});
 process.nextTick(function(){
    
    console.log(5)});
 console.log(6); // 主程序代码
 // 输出2,6,5,3,4,1
 
// 下面这个进阶代码
setTimeout(function(){
    
    console.log(1)},0); // 进入宏任务排序为1
new Promise(function(resolve,reject){
    
    
     console.log(2);
     // promise中执行完resolve()才会执行then(),而这里的resolve在宏任务里,执行完主程序代码后,还得先执行先进入宏队列中的程序
     setTimeout(function(){
    
    resolve()},0) // 进入宏任务排序为2
 }).then(function(){
    
    console.log(3)
 }).then(function(){
    
    console.log(4)});
 process.nextTick(function(){
    
    console.log(5)});
 console.log(6);
 // 输出的是  2 6 5 1 3 4

Look at the execution order in async and await

The code is as follows (example):

async function async1() {
    
    
    console.log(1); 
    await async2();
    console.log(2); //这里要等await执行成功才会执行,进入微任务,排序1
}
async function async2() {
    
    
    console.log(3);
}
console.log(4); //主程序代码
setTimeout(function() {
    
    
    console.log(5);
}, 0) //进入宏任务,最后执行
async1();
new Promise(function(resolve) {
    
    
    console.log(6); // 这句同步执行
    resolve(); 
}).then(function() {
    
    
    console.log(7); //进入微任务,排序2
});
console.log(8); // 主程序代码
// 输出的是  4,1,3,6,8,2,7,5

to sum up

js is a single-threaded language, and its use determines its characteristics. Asynchronous operations use an event loop mechanism to execute synchronous code first, then micro tasks, and finally macro tasks. The tasks in the two task queues are queued and executed in sequence. The code behind await must wait for the promise to return before executing the following code. Await and async are syntactic sugar for generator functions.

Guess you like

Origin blog.csdn.net/qq_42671194/article/details/108660748