我们先来看一个代码片段:
setTimeout(_ => console.log(4))
new Promise(resolve => {
resolve()
console.log(1)
}).then(_ => {
console.log(3)
})
console.log(2)
//输出结果为 1、2、3、4
可以看出Promise
比setTimeout()
先执行。因为Promise定义之后便会立即执行,其后的**.then()是异步里面的微任务**,而setTimeout()是异步的宏任务。异步任务中先执行微任务后执行宏任务。
也就是说, promise
在实例化的过程中所执行的代码都是同步进行的,而 then
中注册的回调才是异步执行的。
在同步代码执行完成后才会去检查是否有异步任务,并执行对应的回调,而微任务又会在宏任务之前执行。
在当前的微任务没有执行完成时,是不会执行下一个宏任务的。
我们再看一个例子:
console.log('script start');
setTimeout(function () {
console.log('setTimeout');
}, 0)
Promise.resolve()
.then(function () {
console.log('promise1');
})
.then(function () {
console.log('promise2');
})
console.log('script end');
它的输出结果为: