欢迎光临散文网 会员登陆 & 注册

JS关于Promise和async await

2023-08-23 16:54 作者:小幻不想码代码  | 我要投稿

复习Promise这块 对于消息队列,宏任务,微任务这块的个人理解,有问题还请各位大佬指正

Promise

运行结果:

1

2

10

5

6

8

9

3

个人理解:微任务的优先级比宏任务优先级高,当微任务没有的时候会执行宏任务,存在微任务时,执行完一个宏任务,会优先执行微任务

  • timeOut2进入宏任务 [timeOut2] [[]] 控制台输出:

  • 执行console.log(1),[timeOut2] [[]] 控制台输出:1

  • p1的状态变为resolve,[timeOut2] [[]] 控制台输出:1

  • 执行console.log(2),[timeOut2] [[]] 控制台输出:1,2

  • timeOut1进入宏任务 [timeOut2,timeOut1] [[]] 控制台输出:1,2

  • p2的状态变为resolve,控制台输出:1,2

  • p2.then加入微任务 [timeOut2,timeOut1] [[p2.then]] 控制台输出:1,2

  • p1.then加入微任务 [timeOut2,timeOut1] [[p2.then,p1.then]] 控制台输出:1,2

  • 执行console.log(10) [timeOut2,timeOut1] [[p2.then,p1.then]] 控制台输出:1,2,10

  • 执行p2.then  [timeOut2,timeOut1] [[p1.then]] 控制台输出:1,2,10,5

  • 执行p1.then  [timeOut2,timeOut1] [[]] 控制台输出:1,2,10,5,6

  • 执行timeOut2  ,执行console.log(8),p3状态变为resolve,p3.then加入微任务。[timeOut1] [[p3.then]] 控制台输出:1,2,10,5,6,8

  • 执行微任务p3.then [timeOut1] [[]] 控制台输出:1,2,10,5,6,8,9

  • 执行timeOut1 控制台输出:1,2,10,5,6,8,9,3

async await

运行结果:

script start

async2 end

Promise

script end

async2 end1

promise1

promise4

promise2

async1 end

promise3

setTimeout

个人理解:执行完await 时 会先把他的then加入微任务  他的then执行完 再执行后面的

  • 执行console.log('script start'),[] [[]] 控制台输出:script start

  • 进入async1,在进入async2,执行console.log('async2 end') async2 end1进入微任务 [] [[async2 end1]] 控制台输出:script start,async2 end

  • 当async2 end1的then执行完  async1 end才会进入微任务

  • setTimeout进入宏任务  [setTimeout] [[async2 end1]] 控制台输出:script start,async2 end

  • 执行console.log('Promise'),promise1进入微任务  [setTimeout] [[async2 end1,promise1]]  控制台输出:script start,async2 end,Promise

  • promise4进入微任务 [setTimeout] [[async2 end1,promise1,promise4]] 控制台输出:script start,async2 end,Promise

  • console.log('script end')    [setTimeout] [[async2 end1,promise1,promise4]] 控制台输出:script start,async2 end,Promise,script end

  • 执行async2 end1  async2()的then进入微任务   [setTimeout] [[promise1,promise4,v]] 控制台输出:script start,async2 end,Promise,script end,async2 end1

  • 执行promise1。promise2进入微任务 [setTimeout] [[promise4,v,promise2]] 控制台输出:script start,async2 end,Promise,script end,async2 end1,promise1

  • 执行promise4。  [setTimeout] [[v,promise2]] 控制台输出:script start,async2 end,Promise,script end,async2 end1,promise1,promise4

  • 执行v, [setTimeout] [[promise2,async1 end]] 控制台输出:script start,async2 end,Promise,script end,async2 end1,promise1,promise4

  • 执行promise2。[setTimeout] [[async1 end,promise3]] 控制台输出:script start,async2 end,Promise,script end,async2 end1,promise1,promise4,promise2

  • 执行async1 end [setTimeout] [[promise3]] 控制台输出:script start,async2 end,Promise,script end,async2 end1,promise1,promise4,promise2,async1 end

  • 执行promise3  控制台输出:script start,async2 end,Promise,script end,async2 end1,promise1,promise4,promise2,async1 end,promise3

  • 执行setTimeout。最后输出:script start,async2 end,Promise,script end,async2 end1,promise1,promise4,promise2,async1 end,promise3,setTimeout


JS关于Promise和async await的评论 (共 条)

分享到微博请遵守国家法律