当前位置:网站首页>What is the execution order of JS asynchronism
What is the execution order of JS asynchronism
2022-06-21 22:00:00 【Yisu cloud】
JS What is the asynchronous execution order
This article mainly introduces “JS What is the asynchronous execution order ”, In daily operation , I believe a lot of people are JS There is some doubt about the asynchronous execution order , Xiao Bian consulted all kinds of materials , Sort out simple and easy-to-use operation methods , I hope to answer ”JS What is the asynchronous execution order ” Your doubts help ! Next , Please follow Xiaobian to learn !
1.js Execution order of , First synchronous then asynchronous
2. Execution order of task queue in asynchronous : First micro task microtask queue , Re macro task macrotask queue
3. call Promise Medium resolve,reject Belongs to the micro task queue ,setTimeout Belongs to macro task queue
Pay attention to the above queue , fifo .
Micro tasks include `process.nextTick` ,`promise` ,`MutationObserver`.
Macro tasks include `script` , `setTimeout` ,`setInterval` ,`setImmediate` ,`I/O` ,`UI rendering`.
stay node In the environment ,process.nextTick Has a higher priority than Promise, That is, it can be simply understood as : After the macro task ends, the... In the micro task queue will be executed first nextTickQueue part , Only then will the... In the micro task be executed Promise part .
javascript Event mechanism

subject 1:
console.log('script start') async function async1() { await async2() console.log('async1 end')}async function async2() { console.log('async2 end')}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('script end')Execution results ?
analysis :
First, execute Synchronization code :
1. First, execute console.log('script start')
2. perform async1() When , Right now async2 function :console.log('async2 end')
3. Sequential execution new Promise() The synchronization function in :console.log('Promise')
4. Finally, execute console.log('script end').
The above code is executed synchronously , Then look at the rest of the asynchronously executed code :
First ,setTimeout yes Macro task , Exclude to the end , The remaining micro tasks :
async function async1() { await async2() console.log('async1 end')}new Promise(resolve => { resolve()}).then(function() { console.log('promise1')}).then(function() { console.log('promise2')})5. Then, according to the first in first out alignment , Execute first await async2() Functions that are blocked later console.log('async1 end')
6. perform promise Of resolve function
new Promise(resolve => { resolve()})That is, the next two then:console.log('promise1') ----console.log('promise2') ;
7. The last thing to do is setTimeout function console.log('setTimeout') ;
in summary , The order in which the above code is executed is :
1.script start >> 2.async2 end >> 3.Promise >> 4.script end >> 5.async1 end >> 6.promise1 >> 7.promise2 >> 8.setTimeout
subject 2:
(function() { setTimeout(() => { console.log(0); }); new Promise(resolve => { console.log(1); setTimeout(() => { resolve(); Promise.resolve().then(() => console.log(2)); console.log(3); }); Promise.resolve().then(() => console.log(4)); }).then(() => { console.log(5); Promise.resolve().then(() => console.log(8)); setTimeout(() => console.log(6)); }); console.log(7); })();1. Also, execute the synchronization code first , And first setTimeout Get rid of :
new Promise(resolve => { console.log(1); Promise.resolve().then(() => console.log(4)); // Micro task }).then(() => { //then The function executes the corresponding resolve It was only executed when console.log(5); Promise.resolve().then(() => console.log(8));// Micro task }); console.log(7);As you can see, execute first :console.log(1);console.log(7);
2. Perform micro tasks
Promise.resolve().then(() => console.log(4));
The code becomes :
(function() { setTimeout(() => { console.log(0); }); new Promise(resolve => { setTimeout(() => { resolve(); Promise.resolve().then(() => console.log(2)); console.log(3); }); }).then(() => { console.log(5); Promise.resolve().then(() => console.log(8)); // This sentence is added setTimeout(() => console.log(6)); });})();Only macro tasks remain ( The micro task is in the macro task , That is, there are no micro tasks outside the macro tasks )
3. perform console.log(0);
4. Re execution new Promise Medium setTimeout, First execute the synchronization function inside :console.log(3)
5. Then execute the above resolve, Corresponding to the following then function :
then(() => { console.log(5); Promise.resolve().then(() => console.log(8)); // This sentence is added setTimeout(() => console.log(6)); }So first execute console.log(5);
The rest are micro tasks and macro tasks , Let's first look at micro tasks :
new Promise(resolve => { resolve(); Promise.resolve().then(() => console.log(2)); }).then(() => { Promise.resolve().then(() => console.log(8)); setTimeout(() => console.log(6)); });Therefore, the micro tasks in the queue are executed first :console.log(2), In execution then Medium console.log(8);
Finally, we will carry out console.log(6)
in summary , The result is
1/7/4/0/3/5/2/8/6
subject 3:
(function() { setTimeout(() => { console.log(0); }); new Promise(resolve => { console.log(1); setTimeout(() => { resolve(); Promise.resolve().then(() => { console.log(2); setTimeout(() => console.log(3)); Promise.resolve().then(() => console.log(4)); }); }); Promise.resolve().then(() => console.log(5)); }).then(() => { console.log(6); Promise.resolve().then(() => console.log(7)); setTimeout(() => console.log(8)); }); console.log(9);})();Explain the following :【 Sync > asynchronous ; Micro task > Macro task 】 First step : Print out 1、9; Pictured

chart a
From the figure a The task queue in :
The second step : Perform micro tasks 3, Print out 5;
The third step : Execute macro task 1, Print out 0,
Step four : Start performing macro tasks 2; Pictured :

chart b
Step five : From the figure b The task queue in , Perform micro tasks 4, Print out 6, Pictured :

chart c
Step six : From the figure c The task queue in , Perform micro tasks 5, Print out 2; Pictured

chart d
From the figure d The task queue of ,
Step seven : Perform micro tasks 6, Print out 7;
Step eight : Perform micro tasks 9, Print out 4;
Step nine : Execute macro task 7, Print out 8;
Step 10 : Execute macro task 8, Print out 3;
The answer is :
1-9-5-0-6-2-7-4-8-3
Here we are , About “JS What is the asynchronous execution order ” That's the end of my study , I hope we can solve your doubts . The combination of theory and practice can better help you learn , Let's try ! If you want to continue to learn more related knowledge , Please continue to pay attention to Yisu cloud website , Xiaobian will continue to strive to bring you more practical articles !
边栏推荐
- Large language models teach agents to evolve. Openai reveals the complementary relationship between the two
- 传承百年经典的瑞吉管家静待您的优雅旅程再次开启
- K - Clairewd’s message HDU - 4300 (EXKMP)
- LeetCode508-出现次数最多的子树元素和-深搜
- 做自媒体视频,如何写出热门爆款标题
- 中微半导体通过注册:年营收11亿 实控人为新西兰国籍
- Jinghe integration has passed the registration: it plans to raise 9.5 billion yuan. Hefei Construction Investment and Midea are shareholders
- There is no sound solution to the loopback when jerryzhi launches Bluetooth [chapter]
- 请问一下,大学生查文献在哪个网站比较好呀?
- 潮流媒体Hypebeast拟曲线上市:作价5.3亿美元 拟第三季完成
猜你喜欢

Which iPad apps can read English literature well?

Enzo高灵敏度检测——Arg8-Vasopressin ELISA kit
![Time modification method for search device of Jerry's Bluetooth transmitter [chapter]](/img/ac/5a1d8cabbc61b24d451753e2f5c8dd.png)
Time modification method for search device of Jerry's Bluetooth transmitter [chapter]
![Jerry's near end tone change problem of opening four channel call [chapter]](/img/03/f08cd660c1c602aa08218c4c791ec3.png)
Jerry's near end tone change problem of opening four channel call [chapter]

InteliJ-IDEA-高效技巧(一)

What is EGFP, green fluorescent protein

天齐锂业通过聆讯:单季净利33亿 蒋卫平夫妇身价超500亿

30 groups of outdoor travel vlog record LUTS color matching preset moody travel LUTS

Fs9935 high efficiency constant current limiting WLED drive IC
![Jerry's problem of playing songs after opening four channel EQ [chapter]](/img/ef/16d630b44df9b1c700bf8cf6acf8b2.png)
Jerry's problem of playing songs after opening four channel EQ [chapter]
随机推荐
Do you really know binary tree? (Part I)
Yx2811 landscape installation driver IC
Worthington胶原蛋白酶原料
P6758 [BalticOI2013] Vim
大型语言模型教会智能体进化,OpenAI这项研究揭示了二者的互补关系
Tutorial on the implementation of smart contracts by solidity (4) -erc1155 contracts
Barbell strategy -- extreme stability and extreme waves
Go language self-study series | golang standard library encoding/xml
Yb5212a charging IC chip sop8
请问一下,大学生查文献在哪个网站比较好呀?
杰理之做蓝牙发射时,将立体声修改成单声道差分输出时,接收端出现卡音【篇】
Excuse me, which website is better for college students to check literature?
Large language models teach agents to evolve. Openai reveals the complementary relationship between the two
Summary of intelligence problems
Jinghe integration has passed the registration: it plans to raise 9.5 billion yuan. Hefei Construction Investment and Midea are shareholders
广东疾控提醒:暑期将至,返粤大学生这样安全“归巢”
12. signal foundation
Go单元测试对数据库CRUD进行Mock测试
杰理之做蓝牙发射的时候,回链没有声音解决方法【篇】
Maximum weight matching of bipartite graph (build a board and stick to two questions)