promise基本理解

 

const pA = () =>{
    return new Promise(resolve=>{
        resolve()
    })
}

const fn1 = () =>{
    fn2()
    console.log(1)
}

const fn2 = async () => {
    await pA()
    console.log('b')
}

async function fn() {
    await fn1()
    console.log('a')
}

fn()


打印顺序 : b   a

理解:  
将async await 写成promise形式

const pA = () => {

    return new Promise(resolve => {

        resolve()

    })

}

const fn1 = () => {

    fn2()

}

const fn2 = () => {

    Promise.resolve(pA()).then(function B(res){

        console.log('pA返回值', res)

        console.log('b', res2)

    })

}

function fn() {

    Promise.resolve(fn1()).then(function A(res) => {

        console.log('fn1返回值', res)

        console.log('a', res2)

    })

}

setTimeout(()=>{console.log('c')}, 0)

fn()

执行时,主线程,执行到fn1(),  其中的then回调B先压入微任务队列(先进先出, 非栈),其后then回调A压入微任务队列, 主代码块执行完毕, 依次执行微任务队列中的‘b’, 'a'
 
另:



如果有多个顺序await, 就会有多个promise的.then, 此时 边执行微任务,碰到新的微任务,会往微任务队列里添加到队尾,此轮微任务的主代码块执行完后,会从微任务队列的队头取任务,如果没有,就从宏任务队列取, (压入的算本宏任务下轮的,跟本微任务没关系了?)

宏任务是每次执行一个, 微任务每次清空队列, 循环往复

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值