await阻塞运行:https://blog.youkuaiyun.com/weixin_34247299/article/details/88119381
原文:https://blog.youkuaiyun.com/yun_hou/article/details/88697954
JavaScript的循环机制
JavaScript有宏任务和微任务。
- 宏任务:script、setTimeOut、setInterval
- 微任务:peomise.then
- 事务的执行顺序是:先执行宏任务,再执行微任务。此外,任务还有同步任务和异步任务。同步任务进入主线程,异步任务进入Event Queue队列(宏任务和微任务是不同的队列)。主线程执行完后从Event Queue队列中取事件放入主线程运行。
setTimeOut:并不是直接把回调函数放入异步队列中,而是等定时器时间到了再放入。此时队列中已经有很多任务了,所以setTimeOut的不能精确执行。
async function async1() {
console.log('async1 start');
await async2();
console.log('asnyc1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(() => {
console.log('setTimeOut');
}, 0);
async1();
new Promise(function (reslove) {
console.log('promise1');
reslove();
}).then(function () {
console.log('promise2');
})
console.log('script end');
index.html:21 script start
index.html:14 async1 start
index.html:19 async2
index.html:27 promise1
index.html:32 script end
index.html:16 asnyc1 end
index.html:30 promise2
index.html:23 setTimeOut
1、执行console.log('script start'),输出script start;
2、执行setTimeout,是一个异步动作,放入宏任务异步队列中;
3、执行async1(),输出async1 start,继续向下执行;
4、执行async2(),输出async2,并返回了一个promise对象,await让出了线程,把返回的promise加入了微任务异步队列,所以async1()下面的代码也要等待上面完成后继续执行;
5、执行 new Promise,输出promise1,然后将resolve放入微任务异步队列;
6、执行console.log('script end'),输出script end;
7、到此同步的代码就都执行完成了,然后去微任务异步队列里去获取任务
8、接下来执行resolve(async2返回的promise返回的),输出了async1 end。
9、然后执行resolve(new Promise的),输出了promise2。
10、最后执行setTimeout,输出了settimeout。