赞
踩
- async function async1 () {
- console.log('async1 start')
- await async2();
- console.log('async1 end')
- }
-
- async function async2 () {
- console.log('async2')
- }
-
- console.log('script start')
-
- setTimeout(function () {
- console.log('setTimeout')
- }, 0)
-
- async1();
-
- new Promise (function (resolve) {
- console.log('promise1')
- resolve();
- }).then (function () {
- console.log('promise2')
- })
-
- console.log('script end')
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
运行结果:
- script start
- async1 start
- async2
- promise1
- script end
- promise2
- async1 end
- setTimeout
首先,要理解宏任务队列和微任务队列,宏任务是代码执行的主线,本来只有一条宏任务线,但如果遇到 setTimeout 之类的就会新建一个宏任务线,然后每个宏任务里面会有一个微任务队列,宏任务在执行过程中如果遇到promise.then()之类的微任务,就会推到当前宏任务的微任务队列当中,在本轮宏任务的同步代码执行完之后,依次执行微任务
首先执行打印script start
然后来到了setTimeout, 新建一条宏任务,排在第一条宏任务后面
执行async1,打印async1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。