文章目录
1. 案例
setTimeout(()=>{
console.log(1)
})
new Promise(resolve => {
resolve()
console.log(2)
}).then(()=>{
console.log(3)
})
console.log(4)
// 结果: 2 4 3 1
我们可以看出来Promise
比setTimeout
先执行, 并且Promise定义之后便会立即执行
promise中的
.then()
是异步里面的微任务
setTimeout()
是异步里面的宏任务
异步任务中先执行微任务, 后执行宏任务
当前的微任务没有执行完成时, 是不会执行下一个宏任务的
Promise
本身是同步进行, 而then
中的回调是异步执行. 执行顺序就是先同步代码执行, 同步执行完成后, 去检查"任务队列"里面是否有异步任务, 并执行相应的回调, '‘任务队列’'里面的微任务又比宏任务提前执行
同步–> 异步(微任务.then–>宏任务setTimeout)
2. 看个综合的例子
console.log('start');
setTimeout(function () {
console.log('setTimeout');
})
Promise.resolve()
.then(()=> {
console.log('then1');
})
.then(()=>{
console.log('then2');
})
console.log('end');
// start
// end
// then1
// then2
// setTimeout