六 异步进阶

110 阅读1分钟

问答题

请描述 event loop(事件循环/事件轮询) 的机制,可画图

什么是宏任务和微任务,两者有什么区别?

Promise有哪三种状态?如何变化?

场景题

promise then catch的连接

// 第一题
Promise.resolve().then(()=>{
  console.log(1)
}).catch(()=>{
  console.log(2)
}).then(() => {
  console.log(3)
})
// 1
// 3

// 第二题
Promise.resolve().then(() => {
  console.log(1)
  throw new Error('error1')
}).catch(() => {
  console.log(2)
}).then(() => {
  console.log(3)
})
// 1
// 2
// 3

// 第三题
Promise.resolve().then(() => {
  console.log(1)
  throw new Error('error1')
}).catch(() => {
  console.log(2)
}).catch(() => {
  console.log(3)
})
// 1
// 2

async/await 语法

async function fn(){
  return 100
}

(async function(){
  const a = fn(); // ?
  console.log('a: ', Object.prototype.toString.call(a), a)
  const b = await fn(); // ?
  console.log('b: ', typeof b, b)
})()

// a: [object Promise] Promise {<fulfilled>: 100}
// b: number 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')
})() // 执行完毕后,打印出哪些内容

image.png

promise和setTimeout的顺序

console.log(100)
setTimeout(()=>{
  console.log(200)
})
Promise.resolve().then(() => {
  console.log(300)
})
console.log(400)

// 100 400  300 200