1.打印顺序
例1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
setTimeout(()=>{
console.log(1);
},0);
Promise.resolve().then(()=>{
console.log(2);
});
Promise.resolve().then(()=>{
console.log(3);
});
console.log(4);
</script>
</body>
</html>
打印结果: 4 2 3 1;
分析:先执行 同步请求 再执行 异步请求 ;异步请求分为 宏任务 和 微任务 ,执行 异步请求 时先执行 微任务 再执行 宏任务 。
例2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
setTimeout(()=>{
console.log(1);
},0);
new Promise((resolve)=>{
console.log(2);
resolve();
}).then(()=>{
console.log(3);
}).then(()=>{
console.log(4);
})
console.log(5);
//2 5 3 4 1
</script>
</body>
</html>
打印结果: 2 5 3 4 1;
分析:先同后异,先微后宏;setTimeout() 和 .then() 里都是执行异步请求;new Promise() 里相当于定义一个函数立即执行,所以执行同步请求先打印 2 5 然后执行异步队列打印 3 4 1;
例3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const fn=()=>
new Promise((resolve,reject)=>{
console.log(1);
let p= new Promise((resolve,reject)=>{
console.log(2);
setTimeout(()=>{
console.log(3);
resolve(4);
},0);
resolve(5);
});
resolve(6);
p.then((arg)=>{
console.log(arg);
})
})
fn().then((arg)=>{
console.log(arg);
})
console.log(7);
//1 2 7 5 6 3
</script>
</body>
</html>
打印结果: 1 2 7 5 6 3;
分析:先同后异,先微后宏;setTimeout() 和 .then() 里都是执行异步请求;new Promise() 里相当于定义一个函数立即执行( 等同于 同步请求 按 顺序执行);setTimeout() 中任务放到宏任务队列中,而 .then() 中任务放到微任务队列中等待,所以按顺序执行同步打印 1 2 7 之后打印异步 5 6 3;
特别注意 setTimeout() 当中的 resolve(4) 没有执行,当 setTimeout() 异步请求执行完时,页面已加载完毕 promise 状态已经确定( 只能有一个状态;以确定 resolve(5) 所以 resolve(4) 不会执行 );