1 async function async1() { 2 console.log('async1 start'); 3 await async2(); 4 console.log('asnyc1 end'); 5 } 6 async function async2() { 7 console.log('async2'); 8 } 9 console.log('script start'); 10 setTimeout(() => { 11 console.log('setTimeOut'); 12 }, 0); 13 async1(); 14 new Promise(function (reslove) { 15 console.log('promise1'); 16 reslove(); 17 }).then(function () { 18 console.log('promise2'); 19 }) 20 console.log('script end');
1 script start 2 async1 start 3 async2 4 promise1 5 script end 6 asnyc1 end 7 promise2 8 setTimeOut
事件的执行顺序,是先执行宏任务,而后执行微任务,这个是基础,任务能够有同步任务和异步任务,同步的进入主线程,异步的进入Event Table并注册函数,异步事件完成后,会将回调函数放入Event Queue中(宏任务和微任务是不一样的Event Queue),同步任务执行完成后,会从Event Queue中读取事件放入主线程执行,回调函数中可能还会包含不一样的任务,所以会循环执行上述操做。
注意: setTimeOut并非直接的把你的回掉函数放进上述的异步队列中去,而是在定时器的时间到了以后,把回掉函数放到执行异步队列中去。若是此时这个队列已经有不少任务了,那就排在他们的后面。这也就解释了为何setTimeOut为何不能精准的执行的问题了。setTimeOut执行须要知足两个条件:node
简单理解就是:promise
了解了什么是宏任务和微任务,就好理解多了,首先执行 宏任务 => 微任务的Event Queue => 宏任务的Event Queue异步
参考博客:https://blog.csdn.net/yun_hou/article/details/88697954async