当前位置:网站首页>Macro task, micro task, async, await principle of interview
Macro task, micro task, async, await principle of interview
2022-06-26 08:01:00 【Small slag bright】
The macro task of interview 、 Micro task 、async、await principle
Macro task of message queue 、 Micro task
1:JS The engine executes tasks in a single thread , That is to say, an assembly line comes down to execute
2: Give priority to synchronization tasks , Asynchronous tasks are placed in message queues
3: There are two types of message queues , Macro queue ( Macro task ), Micro queue ( Dimension task )
4: Micro queues take precedence over macro queues ,
Be careful 1: Even if there are two macro queues , There is a microqueue , Then execute the macro queue first and then , Take out the micro queue of the macro queue for execution , Finally, it points to the next macro queue of the macro queue
Be careful 2:
- Macro queue (dom Callback function for , also ajax, And the timer function )
- Micro queue (promise Callback function , also mutation Callback function )
Message queue example 1
console.log('1')
setTimeout(() => {
console.log('2')
})
Promise.resolve().then(() => {
console.log('3')
})
console.log('4')
// The result is : 1 4 3 2
// analysis :
// log Give priority to synchronization tasks 1 - 4
// setTimeout For macro task Promise For micro task , Micro tasks are executed first , Then first 3 Last 2
Message queue example 2
const home = this.$refs.home
let li = document.createElement('li')
li.innerHTML = ' I added li'
home.insertBefore(li, home.children[0])
console.log('1')
setTimeout(() => {
console.log('2')
alert(' block js perform macro ')
})
Promise.resolve().then(() => {
console.log('3')
alert(' block js perform tiny ')
})
console.log('4')
// The result is : 1 4 3( block js perform tiny ) dom Rendering ( establish dom node li I added li) 2
// Micro task > dom Rendering > Macro task
// analysis :
// log Give priority to synchronization tasks 1 - 4
// setTimeout For macro task Promise For micro task , Micro tasks are executed first , Then first 3 after alret One ( block js perform tiny )
// dom Render li label I added li Finally, execute the macro task 2
Message queue 3
console.log('1')
async function async1() {
await async2()
console.log('async1')
}
async function async2() {
console.log('async2')
}
async1()
setTimeout(function () {
console.log('setTimeout')
}, 0)
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function () {
console.log('promise1')
})
.then(function () {
console.log('promise2')
})
console.log('2')
// result
// // Start with the first round : Synchronization task Use await After grammar Convert to synchronization task ;new Promise The functions inside are synchronization tasks (Promise)
// // Results of the first round of synchronization tasks 1 async2 Promise 2 async1
// In the first round, execute the synchronization task first
// 1 -> await async2() Medium async2() It's a synchronization task , Print out first async2,
// The following code is due to await After processing , Join the micro task message queue -> And then execute ;new Promise The functions inside are synchronization tasks (Promise)
// Finally, perform the final synchronization task 2
// The execution result of the synchronization task :1 async2 Promise 2
// Then execute the micro task :async1 promise1 And then the next one .then() Store in the next micro task
// If there are no other micro tasks, continue to execute the next message queue micro task promise2
// Finally, execute the macro task setTimeout
// The final results :1 async2 Promise 2 async1 promise1 promise2 setTimeout
Message queue 4
setTimeout(() => {
console.log('0')
}, 0)
new Promise(resolve => {
console.log('1')
resolve()
})
.then(() => {
console.log('2')
new Promise(resolve => {
console.log('3')
resolve()
})
.then(() => {
console.log('4')
})
.then(() => {
console.log('5')
})
})
.then(() => {
console.log('6')
})
new Promise(resolve => {
console.log('7')
resolve()
}).then(() => {
console.log('8')
})
// Perform synchronization tasks
// 1 -> 7 Micro task message queue [2,8]
// Perform micro tasks :
// In micro tasks Synchronization task 2 -> Synchronization task 3 -> Next message queue [8,4]
// Execute first 8 -> Next message queue [4]
// Due to micro task 5 I'm not sure , Only wait for micro tasks 4 Only after execution can it be determined , therefore -> Next message queue [4,6]
// Perform micro tasks 4 after , The micro tasks inside 5 To be sure , In the next round of message queue [6,5]
// After performing 6 - 5
// Finally, execute the macro task 0
// result 1 7 2 3 8 4 6 5 0
async And await Principle
- async 、await It's actually right generator Encapsulated a syntax sugar
Multiple asynchronous nesting
function queryData() {
return new Promise(function (resolve) {
resolve(111)
})
}
queryData()
.then(res => {
console.log(' First asynchronous res', res)
return Promise.resolve(222)
})
.then(res => {
console.log(' Second asynchronous res', res)
})
.catch(err => {
console.log('error', err)
})
// If there are multiple asynchronies , Need to use multiple then To handle possible synchronous relationships between asynchronies
es6 And Use yield The way
// Simulate a request
function request() {
return new Promise(resolve => {
setTimeout(() => {
resolve({
data: ' I am a data data '
})
}, 1000)
})
}
// use yield obtain request Value
function* genGetData() {
yield request()
}
const g = genGetData()
const {
value } = g.next()
// console.log('g', g, 'value', value, 'done', done)
// interval 1s Post print {data:" I am a data data "}
value.then(res => {
console.log('data', res)
})
// Output results :data {data: ' I am a data data '}
es7 And async And await Abbreviation
// Use async and await Writing
async function asyncGetData() {
const result = await request()
const result2 = await request()
console.log('result', result, 'result2', result2)
}
asyncGetData()
边栏推荐
- 解决 psycopg2.NotSupportedError: PQconninfo not available in libpq < 9.3
- Rewrite string() method in go language
- [UVM basics] connect of UVM_ Phase execution sequence
- Chapter 5 (array)
- PyTorch-12 GAN、WGAN
- Yyds dry inventory executor package (executor function)
- C#/. Net phase VI 01C Foundation_ 02:vs2019 basic operations, excluding code files, smart tips, data types, differences between float and double, and differences between string and string
- Baoyan postgraduate entrance examination interview - Network
- Nine hours, nine people and nine doors (01 backpack deformation) - Niuke
- Use middleware to record slow laravel requests
猜你喜欢
![[industry cloud talk live room] tomorrow afternoon! Focus on digital intelligence transformation of the park](/img/20/05f0a2dfb179a89188fbb12605370c.jpg)
[industry cloud talk live room] tomorrow afternoon! Focus on digital intelligence transformation of the park
![[NLP] vector retrieval model landing: Bottleneck and solution!](/img/c4/784534e5504dfee1c989d19255c31b.jpg)
[NLP] vector retrieval model landing: Bottleneck and solution!

You can command Siri without making a sound! The Chinese team of Cornell University developed the silent language recognition necklace. Chinese and English are OK

How to design API return codes (error codes)?

The first screen time, you said you optimized it, then you calculated it and showed it to me!

Children play games (greed, prefix and) - Niuke winter vacation training camp

Important reference indicators for data center disaster recovery: RTO and RPO

Okhttp3 source code explanation (IV) cache strategy, disadvantages of Android mixed development

Data governance: from top project to data culture!

WiFi-802.11 2.4G频段 5G频段 信道频率分配表
随机推荐
花指令wp
45. jumping game II dynamic planning DP
Opencv mouse event + interface interaction drawing rectangle polygon selection ROI
Yyds dry inventory kubernetes easy service discovery and load balancing (11)
MFC writes a suggested text editor
Median segmentation (find rules) - Niuke
Is it legal to open an account for compass stock trading software? Is it safe?
Baoyan postgraduate entrance examination interview - Network
有序排列
Chapter VI (pointer)
Livevideostackcon | evolution of streaming media distribution for online education business
Jz-063- median in data stream
Chapter VIII (classes and objects)
Webrtc has become the official standard of W3C and IETF, and mobile terminal development
Google Earth Engine(GEE) 01-中输入提示快捷键Ctrl+space无法使用的问题
Household enterprises use WMS warehouse management system. What are the changes
Okhttp3 source code explanation (IV) cache strategy, disadvantages of Android mixed development
JS Date object
Automatic backup of MySQL database in the early morning with Linux
CMDA 3634 image processing