JavaScript的异步编程

回调函数

发布订阅模式

Promise

手写Promise

手写开始

很多手写版本都是是有setTimeOut去做异步处理,但是setTimeOut属于宏任务,这与Promise是一个微任务相矛盾,所以要选择一种创建微任务的方式去实现。

这里我们有几种选择,一种就是Promise A+规范中提到的,Promise.nextTick(Node端)与MutationObserver(浏览器端),考虑到利用这两种方式需要做环境判断,所以在推荐使用queueMicrotask创建微任务。

Promise核心逻辑实现

原生调用

const promise = new Promise((resolve, reject) => {
    resolve( 'success' )
    reject ( 'err' )
})

promise.then( value => {
    console.log( 'resolve', value)
}, reason => {
    console.log( 'reject', reason)
})
复制代码

基本原理

  1. Promise是一个类,在执行这个类的时候会传入一个执行器,这个执行器会立即执行;
  2. Promise会有三种状态
  • pending 进行中
  • fulfilled 完成
  • rejected 失败
  1. 状态只能由pending -> fulfilled 或者pending -> rejected,且一旦发生改变便不可二次修改;
  2. Promise中使用resolve 和 reject 两个函数来改变状态;
  3. then 方法内部做的事情就是状态判断
  • 如果状态是成功,调用成功回调函数
  • 如果状态是失败,调用失败回调函数

一篇关于手写Promise和分析Promise的好文章

juejin.cn/post/695345…

generator

async await

分析一道题,理解async的实现原理


async function asyncFun1(){
   console.log('async start');
   await asyncFun2()
   await asyncFun3()
   await asyncFun4()
   console.log('async end')
}

async function  asyncFun2(){
    console.log('async await1');  
}

async function asyncFun3(){
    console.log('async await2')
}

async function asyncFun4(){
    console.log('async await3')
}

new Promise((reslove)=>{
    console.log('promise')
    reslove()
}).then(()=>{
    console.log('promise then1')
}).then(()=>{
    console.log('promise then2')
}).then(()=>{
    console.log('promise then3')
}).then(()=>{
    console.log('promise then4')
})

asyncFun1()

复制代码

输出结果为:

promise
async start
async await1
promise then1
async await2
promise then2
async await3
promise then3
async end
promise then4
复制代码

根据上面的输出结果,发现async函数里面从第二个await开始,就和promise.then交替输出,由此可分析出async await是基于微任务实现异步执行的。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享