Browse Source

<hw_promise> done

Mark 1 year ago
parent
commit
6dc6e9ffe9
2 changed files with 73 additions and 0 deletions
  1. 15 0
      12/index.html
  2. 58 0
      12/main.js

+ 15 - 0
12/index.html

@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+   <meta charset="UTF-8">
+   <meta http-equiv="X-UA-Compatible" content="IE=edge">
+   <meta name="viewport" content="width=device-width, initial-scale=1.0">
+   <title>Document</title>
+</head>
+
+<body>
+   <script src="main.js"></script>
+</body>
+
+</html>

+ 58 - 0
12/main.js

@@ -0,0 +1,58 @@
+// Javascript Async: Promise Homework
+// fetch basic 
+
+fetch('https://swapi.dev/api/people/1/')
+   .then((res) => res.json())
+   .then((luke) => {
+      basic(document.body, luke)
+   });
+
+function basic(dom, json) {
+   const table = document.createElement("table");
+   dom.appendChild(table);
+   for (let key in json) {
+      const tr = document.createElement("tr")
+      const td = document.createElement("td");
+      tr.innerText = key;
+      td.innerText = json[key];
+      tr.appendChild(td);
+      table.appendChild(tr)
+   }
+}
+
+// myfetch
+
+myfetch('https://swapi.dev/api/people/1/')
+   .then(luke => console.log(luke))
+function myfetch(url) {
+   return new Promise(function (resolve, reject) {
+      const xhr = new XMLHttpRequest();
+      xhr.open('GET', url, true);
+      xhr.onreadystatechange = function () {
+         if (xhr.readyState != 4) {
+            return;
+         }
+         if (xhr.status == 200) {
+            resolve(JSON.parse(xhr.responseText));
+         } else {
+            reject('err')
+         }
+      }
+      xhr.send();
+   })
+}
+
+// race
+let mfetch = new Promise((resolve, reject) => {
+   setTimeout(() => {
+      fetch('https://swapi.dev/api/people/1/')
+         .then(res => res.json())
+         .then(luke => console.log(luke))
+   }, Math.random() * 1000);
+});
+let delay = new Promise((resolve, reject) => {
+   setTimeout(() => resolve('delay'), Math.random() * 1000);
+});
+Promise.race([mfetch, delay]).then((res) => {
+   console.log(res);
+});