30_async_await.html 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // setTimeout(() => {
  11. // console.log('定时函数');
  12. // },1000)
  13. // console.log("同步代码");
  14. //
  15. // async/await 异步优化处理方案
  16. // (将异步代码转换为同步执行)
  17. // async 写在函数前面,将函数转换为异步函数
  18. async function foo(){
  19. // await 写在 Promise 前面,等待 Promise 执行完成 ,然后继续执行后面的代码
  20. await new Promise((resolve) => {
  21. setTimeout(() => {
  22. console.log('定时函数');
  23. resolve();
  24. },1000)
  25. })
  26. console.log("同步代码");
  27. // setTimeout(() => {
  28. // console.log('定时函数');
  29. // },1000)
  30. // console.log("同步代码");
  31. }
  32. foo();
  33. // async await 他是promise的语法糖
  34. async function name(params) {
  35. // await 之前代码属于同步代码 (类似于new Promise)
  36. await new Promise((resolve) => {
  37. setTimeout(() => {
  38. console.log('定时函数');
  39. resolve();
  40. },1000)
  41. })
  42. // await 之后代码属于异步代码(Promise.then())
  43. }
  44. new Promise((resolve) => {
  45. setTimeout(() => {
  46. console.log('定时函数');
  47. resolve();
  48. },1000)
  49. }).then(() => {
  50. console.log("同步代码");
  51. })
  52. </script>
  53. </body>
  54. </html>