JS基础-异步

134 阅读2分钟

基础

同步和异步有什么不同

  • 同步阻塞线程
  • 异步不阻塞线程

异步有哪些应用场景

  • 网络请求
  • 图片加载等

event loop

console.log(1)

setTimeout(()=>{
    console.log(3)
}, 1000)

console.log(2)
  1. console.log(1) 被推入 call task
  2. 调用console.log(1)打印1
  3. setTimeout 被推入 call task
  4. 执行setTimeout
  5. ()=>{console.log(3)} 等待执行
  6. console.log(2) 被推入 call task
  7. 执行console.log(2) 打印2
  8. 1秒后()=>{console.log(3)} 被推入 callback queue
  9. callback queue执行

总结: 将代码推入 call task, 运行同步代码, 异步代码进入等待, 同步代码执行完成, 去执行callback queue。 重复以上动作, 异步代码完成等待会被推入callback queue

宏任务&微任务

哪些方法能产生宏任务,哪些能产生微任务?

  • 宏任务:setTimeout、setInterval、ajax、dom事件(click等调用一些事件方法)
  • 微任务:Promise、async-await

以下输出顺序?

console.log(1)

setTimeout(()=>{
    console.log(3)
}, 1000)
Promise.resolve().then(()=>{console.log(4)})

console.log(2)

答案: 1、2、4、3

为什么? 结合event loop说明

  • setTimeout产生的是宏任务
  • Promise 产生的是微任务
  • 前面讲过evnet loop带入就好
  • 在宏任务结束之前, 会将当前宏任务中产生的可执行微任务进行执行,
  • 宏任务结束后, 会释放一段时间去执行dom渲染, 或者垃圾回收机制等(这条可不讲, 如果要讲最好了解一下垃圾回收机制, 不然很可能被问) 之后文章会写垃圾回收
  • 然后执行callback queue中的第一个任务, 重复上述动作

Promise

以下三组Promise分别打印的是什么

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

答案: 一组:1、2; 二组:1、3;三组:1、3、2;

为什么?

详细解析Promise基础

  • Promise 一共有三种状态:pending、resolved、rejected
  • Promise 状态改变不可逆
  • Promise then、catch都会返回一个 “新的Promise”

“新的Promise” 请看下方代码理解

const p = Promise.reject(1)
const p1 = p.catch()
// p !== p1
  • then、catch返回的Promise状态都为resolved,如果then、catch回调中存在错误, 将返回Promise状态都为reject

讲解开头的题目: 一组

Promise.resolve().then(()=>{
    console.log(1)
}).then(()=>{
    console.log(2)
}).catch(()=>{
    consle.log(3)
})
  1. Promise.resolve() 返回Promise:resoled执行then
  2. Promise.then 返回Promise:resoled, 继续执行
  3. Promise.then 返回romise:resoled, 后续无then,所以结束

组二

Promise.resolve().then(()=>{
    console.log(1)
    throw new Error('')
}).then(()=>{
    console.log(2)
}).catch(()=>{
    console.log(3)
})
  1. Promise.resolve() 返回Promise:resoled执行then
  2. Promise.then 返回Promise:rejected,继续执行
  3. Promise.catch 返回Promise:resolved,后续无then所以结算

第三组就自己根据前面的讲解自己解读吧