- 请描述 event loop(事件循环/事件轮询)的机制,可画图
- 什么是宏任务和微任务,两者有什么区别
- Promise 有哪三种状态,如何变化
- 场景提- promise then 和 catch 的连接
无论是 then 还是 catch, 只要没有报错就是 resolved 状态
// 第一题Promise.resolve().then(() => {console.log(1)}).catch(() => {console.log(2)}).then(() => {console.log(3)})// 1// 3// Promise.resolve() 是 resolved状态, 所以执行 then()// then()执行,里面无报错,所以 then() 是 resolved 状态,// 所以下个 catch() 不执行,执行下个then()// then()执行,里面无报错,所以 then() 是 resolved 状态// 第二题Promise.resolve().then(() => {console.log(1)throw new Error('error1')}).catch(() => {console.log(2)}).then(() => {console.log(3)})// 1// 2// 3// Promise.resolve() 是 resolved状态, 所以执行 then()// then()执行,里面有报错,所以 then() 是 rejected 状态,// 所以下个 catch() 执行,里面无报错,所以 catch() 是 resolved 状态,// 所以执行下个 then()// then()执行,里面无报错,所以 then() 是 resolved 状态// 第三题Promise.resolve().then(() => {console.log(1)throw new Errow('error1')}).catch(() => {console.log(2)}).catch(() => {console.log(3)})// 1// 2// Promise.resolve() 是 resolved状态, 所以执行 then()// then()执行,里面有报错,所以 then() 是 rejected 状态,// 所以下个 catch() 执行,里面无报错,所以 catch() 是 resolved 状态,// 所以执行下个 catch 不执行()/
- 场景题 - async/await ```javascript // 第一题 async function fn() { return 100 }
(async function() { const a = fn() console.log(a) // ? Promise对象
const b = await fn() console.log(b) // ? 100 })()
// 第二题 (async function() { console.log(‘start’)
const a = await 100 console.log(‘a=’, a)
const b = await Promise.resolve(200) console.log(‘b=’, b)
const c = await Promise.reject(300) console.log(‘c=’, c)
console.log(‘end’) })() // start // a=100 // b=200 // c=300 // end
6. 场景题 - promise 和 setTimeout 的顺序```javascriptconsole.log(100)setTimeout(() => {console.log(200)})Promise.resolve().then(() => {console.log(300)})console.log(400)// 100// 400// 300// 200
场景题 - 外加 async/await 的顺序问题 ```javascript async function async1() { console.log(‘async1 start’) // 2
await async2()
// await 后面的都是一个异步 微任务1 console.log(‘async1 end’) // 6 }
async function async2() { console.log(‘async2’) // 3 }
console.log(‘script start’) // 1
setTimeout(function() { // 宏任务 1 console.log(‘setTimeout’) // 8 }, 0)
async1()
// 初始化 promise 是,传入的函数会立刻被执行 new Promise(function(resolve) { console.log(‘promise1’) // 4
resolve() }).then(function() { // 微任务 2 console.log(‘promise2’) // 7 })
console.log(‘script end’) // 5
// 同步代码执行完毕 // 微任务 microTask // 触发 DOM 渲染 // 触发event loop // 宏任务 macroTask
```
