19_async await.html 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. 1.进入到 async1,发现同步任务,输出'async1 start'
  11. 2.遇到了await,进入到async2,碰到定时器,加入到异步队列里面的宏任务
  12. 3.在async2 有一个同步任务 直接输出'async2'
  13. 4.由于await 阻塞了后面代码的执行 将后面的代码加入微任务 所以向下去找
  14. 5.碰到了定时器 加入到宏任务里
  15. 6.碰到同步任务 输出'start'
  16. 7.同步代码执行完毕 先执行微任务
  17. 8.先输出微任务里面的 同步任务 输出'async1 end'
  18. 9.微任务里面有定时器 加入到宏任务里
  19. 10.微任务执行完毕 执行宏任务
  20. 11.宏任务队列里面有3个任务
  21. 12.按照顺序执行 timer2=>timer3=>timer1
  22. async 函数
  23. 1.函数返回值返回Promise对象
  24. 2.Promise对象结果由async里面的返回值决定
  25. await函数
  26. 1.必须写在async里面
  27. 2.如果遇到await函数 函数后面的代码会被阻止 加入微任务队列里面
  28. <script>
  29. /* async function timeout(){
  30. // throw new Error('rejected')
  31. return 'hello word'
  32. }
  33. timeout().then(val =>{
  34. console.log(val)
  35. })
  36. // console.log(timeout())
  37. console.log(1111) */
  38. /* await 方法 会阻塞函数内部处于它后面的代码 */
  39. /* async function fn1(){
  40. console.log(1)
  41. await fn2()
  42. console.log(2)//加入微任务队列
  43. }
  44. async function fn2(){
  45. console.log('fn2')
  46. }
  47. fn1()
  48. console.log(3) */
  49. /* async function async1() {
  50. console.log('async1 start')
  51. await async2()
  52. console.log('async1 end')
  53. setTimeout(() => {
  54. console.log('timer1')
  55. }, 0)
  56. }
  57. async function async2() {
  58. setTimeout(() => {
  59. console.log('timer2')
  60. }, 0)
  61. console.log('async2')
  62. }
  63. async1()
  64. setTimeout(() => {
  65. console.log('timer3')
  66. }, 0)
  67. console.log('start') */
  68. /* await function fn2(){
  69. console.log(2)
  70. }
  71. fn2() */
  72. /* async function fn1(){
  73. console.log(333)
  74. await fn2()
  75. console.log(111)
  76. }
  77. async function fn2(){
  78. throw new Error('rejected')
  79. }
  80. fn1()
  81. console.log(2222) */
  82. async function fn1(){
  83. console.log(1)
  84. await fn2()
  85. console.log(2)
  86. setTimeout(()=>{
  87. console.log(3)
  88. },0)
  89. }
  90. async function fn2(){
  91. console.log(4)
  92. await fn3()
  93. console.log(5)
  94. }
  95. async function fn3(){
  96. setTimeout(()=>{
  97. console.log(6)
  98. },0)
  99. }
  100. fn1()
  101. console.log(7)
  102. //1475263
  103. //1472563
  104. </script>
  105. </body>
  106. </html>