21.async await.html 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. /**
  11. * es6 => Promise => 回调地狱
  12. * es7 => async await
  13. * async 在函数前添加async 使函数变成异步函数
  14. * await 不是说一定要和async一起使用 后面一般跟表达式 如何async一起使用的话 await后是微任务
  15. */
  16. // console.log(2);
  17. // setTimeout(() => {
  18. // console.log(3);
  19. // }, 0);
  20. // async function fn1() {
  21. // throw new Error("报错")
  22. // // return '111';
  23. // }
  24. // fn1().then(()=>{
  25. // console.log(2)
  26. // })
  27. // fn1().catch(()=>{
  28. // console.log("3")
  29. // })
  30. console.log(1);
  31. function count(num) {
  32. return new Promise((resolve, reject) => {
  33. setTimeout(() => {
  34. resolve(num * 2);
  35. }, 1000);
  36. });
  37. }
  38. setTimeout(() => {
  39. console.log(3);
  40. }, 0);
  41. async function fn2() {
  42. try {
  43. let total1 = await count(2);
  44. let total2 = await count(20);
  45. let total3 = await count(200);
  46. console.log(total1, total2, total3);
  47. } catch {
  48. console.log("失败");
  49. }
  50. }
  51. fn2();
  52. console.log("完成");
  53. </script>
  54. </body>
  55. </html>