| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- // setTimeout(() => {
- // console.log('定时函数');
- // },1000)
- // console.log("同步代码");
- //
- // async/await 异步优化处理方案
- // (将异步代码转换为同步执行)
- // async 写在函数前面,将函数转换为异步函数
- async function foo(){
- // await 写在 Promise 前面,等待 Promise 执行完成 ,然后继续执行后面的代码
- await new Promise((resolve) => {
- setTimeout(() => {
- console.log('定时函数');
- resolve();
- },1000)
- })
- console.log("同步代码");
- // setTimeout(() => {
- // console.log('定时函数');
- // },1000)
- // console.log("同步代码");
- }
- foo();
- // async await 他是promise的语法糖
- async function name(params) {
- // await 之前代码属于同步代码 (类似于new Promise)
- await new Promise((resolve) => {
- setTimeout(() => {
- console.log('定时函数');
- resolve();
- },1000)
- })
- // await 之后代码属于异步代码(Promise.then())
- }
- new Promise((resolve) => {
- setTimeout(() => {
- console.log('定时函数');
- resolve();
- },1000)
- }).then(() => {
- console.log("同步代码");
- })
- </script>
- </body>
- </html>
|