fengchuanyu 14 godzin temu
rodzic
commit
4366514446
1 zmienionych plików z 60 dodań i 0 usunięć
  1. 60 0
      8_ES6/30_async_await.html

+ 60 - 0
8_ES6/30_async_await.html

@@ -0,0 +1,60 @@
+<!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>