Promise阅读代码理解
Bitgeek 2024-05-01 vue3vuevite
# Promise阅读代码理解
- Promise、async、await 的基础
- 对 Event Loop、宏任务、微任务的理解
# 知识点
- JS 执行顺序:自上而下、先同步再异步、先微任务后宏任务
- new Promise() -> Promise.resolve()
- then 和 catch 内部没有 throw new Error 相当于 resolve
- async function 相当于返回 Promise.resolve()
- await 后面的代码都是异步的
# 阅读代码 1
Promise.resolve()
Promise.reject().then((data) => {
console.log(data)
}).catch((e) => {
console.log(e)
})
# 执行结果
# 解释:因为他走的是reject()失败,执行的是catch方法
# 阅读代码 2
Promise.resolve()
.then(() => {
console.log(1);
throw new Error("error1");
})
.catch(() => {
console.log(2);
})
.then(() => {
console.log(3);
});
# 执行结果
# 解释:最一开始走的是resolve()成功=>then方法打印1,throw new Error("error1"):是指抛出一个错误=>catch方法打印2,接着走then方法,只要不抛出错误不reject,就执行then()
# 阅读代码 3
async function async1() {
console.log('async1 start')
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2')
}
console.log('script start')
setTimeout(() => {
console.log('setTimeout')
}, 0)
async1()