当前位置:网站首页>JS knowledge blind spot | understanding of async & await

JS knowledge blind spot | understanding of async & await

2022-06-21 07:09:00 A touch of sunshine &

async await The implementation process of

Never paid attention to await This keyword , Only know await How to use 、await Is similar to the resolve The role of successful callback , In the previous implementation, through new Promise(resolve => resolve()), But after optimization, it becomes Promise.resolve(). Ask questions about the cycle of events during the interview .
The following questions do not relate to async and Promise Priority judgment of , Just common synchronous and asynchronous judgment , To re recognize Generator+Promise == async And await The process of

setTimeout(() => {
     console.log(0)}, 0)
{
     //Node  It is not allowed to write self executing anonymous functions directly , Should be placed in curly braces 
	(async function(){
    
		console.log(1)
		await Promise.resolve()
		console.log(2)
	})()
}

console.log(3)

new Promise(reslve => {
    
	console.log(4)
}).then(res => {
    
	console.log(5)
}).catch(err => {
    
	console.log(6)
})


const p = new Promise((resolve, reject) => {
    
	console.log(7)
	resolve(8)
})

p.then(res => {
    
	console.log(res)
}).then(res => {
    
	console.log(9)
})
p.then(res => {
    
	console.log(10)
})

{
    
	(async () => {
    
		console.log(11)
		await Promise.resolve(333)
		console.log(12)
	})()
}

analysis

Be careful :async The decorated function is a function executed synchronously , But when it comes to await,await After that, all code blocks become micro tasks , If we meet again await, This is the last await Of then The task , Micro tasks , At this point, the generator and Promise Explain in combination .

Review generator

Use function* Definition , Another special syntax in the class *[Symbol.iterator](){} || *iterator(){} It's OK, too . By keyword yield Split code blocks , By keyword yield Divided code blocks are like functions one by one .

  • Generators are special iterators
  • adopt yield Control code operation ,yield It's like a function , Able to receive and return . const msg = yield 'Hello JS'
function request(msg) {
     
	return new Promise((resolve, reject) => {
     
		resolve(msg)
	})
}
function* getBanners() {
     
 //  Every time yield All represent then Chained code blocks 
 let msg = yield "Hello JS";
 msg = yield request(msg + "aaa");
 msg = yield request(msg + "bbb");
 msg = yield request(msg + "ccc");
 console.log(msg);
}
//  Manual implementation , Match each step with Promise Connect 
const generator = getBanners("Hello JS");
Promise.resolve(generator.next().value).then((res) => {
     
 generator.next(res).value.then((res) => {
     
   generator.next(res).value.then((res) => {
     
     generator.next(res).value.then((res) => {
     
       generator.next(res); //  Finally, you can call 
     });
   });
 });
});

//  automatically ( How many times does the recursive method yield, Just calculate )
let val = generator.next().value /*  initial next */
function co(generator) {
     
 if (val === undefined) {
      /* base case */
   return ;
 }

 if (val instanceof Promise) {
     
   val.then(res => {
     
     val = generator.next(res).value
     co(generator)
   })
   return ;
 }
 val = generator.next(val).value
 co(generator)
}
co(generator)
  • After analyzing this stage , Basically, it realizes async and await The function of , Simply speaking yield Namely await The function of , At the same time, it can be found from the implementation ,await Just like that. resolve The grammar sugar of , If it is a normal value, then wrap a layer Promise.resolve Can finish Promise Transformation of objects .
  • summary :async And await == Promise + Generator await The following code will be in the form of micro tasks .

answer

The main thing is async and await Synchronous and asynchronous ( Micro task , Than Promise Higher priority ).

1
3
4
7
11
2
8
10
12
9  Be careful : This is because the arrow function returns the last line , There is a return value , Even if there is no explicit resolve
0
原网站

版权声明
本文为[A touch of sunshine &]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210707479365.html