33.async await.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. <script>
  11. /**
  12. * async await
  13. * async 在函数前添加async使函数变成异步 默认状态成功
  14. * await 不仅局限于使用在async里 后面跟表达式 如果和async一起使用 await后的内容 属于微任务
  15. */
  16. // async await 使用的是try{成功}catch{异常}
  17. //await会阻塞后面的方法
  18. /***
  19. * await 后 Promise时 进入微任务
  20. * await 不是Promise 正常执行
  21. * */
  22. // async function fn1() {
  23. // return 111;
  24. // }
  25. // fn1().then(val=>{
  26. // console.log(val,'val')
  27. // });
  28. // async function fn2() {
  29. // throw new Error("reject");
  30. // }
  31. // console.log(fn2());
  32. // fn1();
  33. // console.log(222);
  34. function count(num) {
  35. return new Promise((resolve,reject)=>{
  36. setTimeout(()=>{
  37. resolve(num * 2);
  38. },1000)
  39. })
  40. }
  41. async function fn3() {
  42. let total1 = await count(2);
  43. let total2 = await count(20);
  44. let total3 = await count(12);
  45. console.log(total1,total2,total3);
  46. }
  47. fn3();
  48. console.log("333")
  49. </script>
  50. </body>
  51. </html>