js 关于 Promise、generator、async/await 的简单对比

client.html

 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       const xhr = new XMLHttpRequest();
11 
12       /* 封装一个 api */
13 
14       function api({ url, params }) {
15         return new Promise((resolve, reject) => {
16           xhr.open("POST", url, true);
17           xhr.onreadystatechange = function () {
18             if (xhr.readyState === 4 && xhr.status === 200) {
19               resolve(xhr.responseText);
20             }
21           };
22           xhr.onerror = function (err) {
23             reject(err);
24           };
25           // 这里会触发预检请求,需要服务端做相关配置
26           // 或者使用 text/plain
27           xhr.setRequestHeader("Content-Type", "application/json");
28           xhr.send(JSON.stringify(params));
29         });
30       }
31 
32       /* 调用 api */
33 
34       function api_1(params) {
35         return api({
36           url: "http://localhost/a.json",
37           params,
38         });
39       }
40 
41       function api_2(params) {
42         return api({
43           url: "http://localhost/b.json",
44           params,
45         });
46       }
47 
48       function api_3(params) {
49         return api({
50           url: "http://localhost/c.json",
51           params,
52         });
53       }
54 
55       /* 使用 Promise 控制异步流程 */
56 
57       api_1({ step: 0 })
58         .then((info_1) => api_2(JSON.parse(info_1)))
59         .then((info_2) => api_3(JSON.parse(info_2)))
60         .then((info_3) => console.log(JSON.parse(info_3)));
61 
62       /* 用 generator 控制异步流程 */
63 
64       setTimeout(() => {
65         function* G() {
66           const info_1 = yield api_1({ step: 10 });
67           const info_2 = yield api_2(JSON.parse(info_1));
68           const info_3 = yield api_3(JSON.parse(info_2));
69           return info_3;
70         }
71 
72         const g = G();
73         g.next().value.then((info_1) => {
74           g.next(info_1).value.then((info_2) => {
75             g.next(info_2).value.then((info_3) => {
76               const res = g.next(info_3).value;
77               console.log(JSON.parse(res));
78             });
79           });
80         });
81       }, 400);
82 
83       /* 使用 async/await 控制异步流程 */
84 
85       setTimeout(() => {
86         async function apis() {
87           const info_1 = await api_1({ step: 100 });
88           const info_2 = await api_2(JSON.parse(info_1));
89           const info_3 = await api_3(JSON.parse(info_2));
90           return info_3;
91         }
92 
93         apis().then((info) => console.log(JSON.parse(info)));
94       }, 800);
95     </script>
96   </body>
97 </html>

 

server.js

 1 const http = require("http"); // node内部模块,用来创建http服务器
 2 
 3 const server = new http.Server();
 4 
 5 server.on("request", (req, res) => {
 6   const url = req.url;
 7   const suffix = url.match(/(?<=\.)\w+/)[0]; // 获取文件后缀
 8   let mimeType = "";
 9   switch (suffix) {
10     case "json":
11       mimeType = "application/json";
12       break;
13     default:
14       mimeType = "text/javascript";
15   }
16 
17   res.writeHead(200, {
18     "Content-Type": mimeType,
19     "Access-Control-Allow-Origin": "*",
20     // 预检请求可以接受的请求头
21     "Access-Control-Allow-Headers": "Content-Type",
22   });
23 
24   let info = null;
25 
26   req.on("data", (data) => {
27     info = JSON.parse(data.toString());
28   });
29   req.on("end", () => {
30     // 预检请求不发送响应体
31     if (req.method === "OPTIONS") {
32       res.end();
33       return false;
34     }
35     res.write(JSON.stringify({ step: ++info.step }));
36     res.end();
37   });
38 });
39 
40 server.listen(80);

 

posted @ 2023-10-16 23:35  万物有序  阅读(16)  评论(0编辑  收藏  举报