文章目录
- 1 原理图
- 2 说明
- 3 相关面试题
- 3.1 面试题1
- 3.2 面试题2
- 3.3 面试题3
- 3.4 面试题4
1 原理图
2 说明
- JS 中用来存储待执行回调函数的队列包含 2 个不同特定的队列:宏队列和微队列。
- 宏队列:用来保存待执行的宏任务(回调),比如:定时器回调 / DOM事件回调 / ajax 回调。
- 微队列:用来保存待执行的微任务(回调),比如:promise的回调 / MutationObserver的回调。
- JS 执行时会区别这 2 个队列:
- JS 引擎首先必须先执行所有的初始化同步任务代码。
- 每次准备取出第一个宏任务执行前,都要将所有的微任务一个一个取出来执行。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>10_宏队列与微队列</title>
</head><body><script>setTimeout(() => { console.log('timeout callback1()'); Promise.resolve(3).then(value => { console.log('Promise onResolved3()', value); })}, 0);setTimeout(() => { console.log('timeout callback2()'); }, 0);Promise.resolve(1).then(value => { console.log('Promise onResolved1()', value); })Promise.resolve(1).then(value => { console.log('Promise onResolved2()', value); })</script>
</body></html>
3 相关面试题
3.1 面试题1
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>11_Promise相关面试题1</title>
</head><body><script type="text/javascript">setTimeout(() => { console.log(1);}, 0)Promise.resolve().then(() => { console.log(2);})Promise.resolve().then(() => { console.log(4);})console.log(3); </script>
</body></html>
3.2 面试题2
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>11_Promise相关面试题2</title>
</head><body><script type="text/javascript">setTimeout(() => { console.log(1);}, 0)new Promise((resolve) => {console.log(2); resolve();}).then(() => { console.log(3);}).then(() => { console.log(4);})console.log(5); </script>
</body></html>
3.3 面试题3
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>11_Promise相关面试题3</title>
</head><body><script type="text/javascript">const first = () => (new Promise((resolve, reject) => {console.log(3); let p = new Promise((resolve, reject) => {console.log(7); setTimeout(() => { console.log(5);resolve(6);}, 0)resolve(1); })resolve(2); p.then((arg) => { console.log(arg); })}))first().then((arg) => { console.log(arg); })console.log(4); </script>
</body></html>
3.4 面试题4
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>11_Promise相关面试题4</title>
</head><body><script type="text/javascript">setTimeout(() => { console.log("0");}, 0)new Promise((resolve, reject) => {console.log("1"); resolve();}).then(() => { console.log("2");new Promise((resolve, reject) => {console.log("3"); resolve();}).then(() => { console.log("4");}).then(() => { console.log("5");})}).then(() => { console.log("6");})new Promise((resolve, reject) => {console.log("7");resolve();}).then(() => { console.log("8");})</script>
</body></html>