来直接看面试题 示例代码如下:
<!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练习</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("执行1")
//resolve("resol同步执行1_resolve参数——settimeout_out")
setTimeout(() => {
console.log("宏任务里面返回微任务 fuilled状态2")
resolve("resol同步执行1_resolve参数——settimeout")
})
})
promise.then((result) => {
console.log("result结果执行3",result)
})
const promise2 = new Promise(resolve => {
console.log('同步执行2');
resolve('同步执行2_resolve参数');
}).then(tip => {
//console.log('then2_1', tip);
console.log("执行2")
return 'then2_1'+tip
}).then(tip => {
//console.log('then2_2', tip);
console.log("执行4")
}).then(tip =>{
//console.log('then2_3', tip);
console.log("执行6")
})
setTimeout(() => {
console.log("setTimeout执行")
promise2.then(tip => {
console.log('setTimeout执行_then2_3', tip);
})
});
const promise3 = new Promise(resolve => {
console.log('同步执行3');
resolve('同步执行3——resolve');
}).then(tip => {
//console.log('then3_1', tip);
console.log("执行3")
return tip+"-return"
}).then(tip => {
//console.log('then3_2', tip);
console.log("执行5")
}).then((tip)=>{
//console.log('then3_3', tip);
console.log("执行7")
})
setTimeout(() => {
console.log("主线程里面的setTimeout")
promise3.then(tip => {
console.log('then3_3', tip);
})
});
console.log("==========start_main_end===========")
</script>
</body>
</html>
运行效果如下
输出结果.png
网友评论