<script>
Promise.resolve('1')
.then(res => {
console.log(res)
})
.finally(() => {
console.log('finally')
})
Promise.resolve('2')
.finally(() => {
console.log('finally2')
})
.then(res => {
console.log('finally2后面的then函数,', res)
})
</script>
代码输出结果
1
finally2
finally
finally2后面的then函数, 2
其实一开始百思不得其解,不应该是按顺序执行吗
先1,然后执行finally,输出finally,为什么先输出finally2呢?因为finally本质是then方法的特例,其实把上面的finally换成then,输出的顺序也是这样的。then是一个微任务,finally当然也是,当我们执行完
.then(res => {
console.log(res)
})
之后,遇到了
.finally(() => {
console.log('finally')
})
就会把它放到微任务队列里,等待下一轮的执行,而
Promise.resolve('2')
.finally(() => {
console.log('finally2')
})
和
Promise.resolve('1')
.then(res => {
console.log(res)
})
是同一轮的。