來直接看面試題 示例代碼如下:
<!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>Promise跟setTimeout練習(xí)</title>
</head>
<body>
<script type="text/javascript">
console.log("==========start_main===========")
setTimeout(() => {
console.log("主線程最先開始的setTimeout")
promise3.then(tip => {
console.log('主線程最先開始的setTimeout——promise3', tip);
})
});
const promise = new Promise((resolve, reject) => {
console.log("執(zhí)行1")
//resolve("resol同步執(zhí)行1_resolve參數(shù)——settimeout_out")
setTimeout(() => {
console.log("宏任務(wù)里面返回微任務(wù) fuilled狀態(tài)2")
resolve("resol同步執(zhí)行1_resolve參數(shù)——settimeout")
})
})
promise.then((result) => {
console.log("result結(jié)果執(zhí)行3",result)
})
const promise2 = new Promise(resolve => {
console.log('同步執(zhí)行2');
resolve('同步執(zhí)行2_resolve參數(shù)');
}).then(tip => {
//console.log('then2_1', tip);
console.log("執(zhí)行2")
return 'then2_1'+tip
}).then(tip => {
//console.log('then2_2', tip);
console.log("執(zhí)行4")
}).then(tip =>{
//console.log('then2_3', tip);
console.log("執(zhí)行6")
})
setTimeout(() => {
console.log("setTimeout執(zhí)行")
promise2.then(tip => {
console.log('setTimeout執(zhí)行_then2_3', tip);
})
});
const promise3 = new Promise(resolve => {
console.log('同步執(zhí)行3');
resolve('同步執(zhí)行3——resolve');
}).then(tip => {
//console.log('then3_1', tip);
console.log("執(zhí)行3")
return tip+"-return"
}).then(tip => {
//console.log('then3_2', tip);
console.log("執(zhí)行5")
}).then((tip)=>{
//console.log('then3_3', tip);
console.log("執(zhí)行7")
})
setTimeout(() => {
console.log("主線程里面的setTimeout")
promise3.then(tip => {
console.log('then3_3', tip);
})
});
console.log("==========start_main_end===========")
</script>
</body>
</html>
運(yùn)行效果如下

輸出結(jié)果.png