Browse Source

HW YB2NKR8B2LL done

Varvara Huza 3 years ago
parent
commit
bc62d62dc6
2 changed files with 90 additions and 0 deletions
  1. 13 0
      Homework_13/index.html
  2. 77 0
      Homework_13/main.js

+ 13 - 0
Homework_13/index.html

@@ -0,0 +1,13 @@
+<!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>
+    <script src="main.js" defer></script>
+</head>
+<body>
+    
+</body>
+</html>

+ 77 - 0
Homework_13/main.js

@@ -0,0 +1,77 @@
+//fetch basic/improved
+fetch('https://swapi.dev/api/people/1/')
+  .then(res => res.json())
+  .then(luke => (function createTable(parent, object) {
+
+    let makeButton = (container, link) => {
+      let button = document.createElement('button')
+      button.innerText = 'create table'
+      button.dataset.link = link
+      button.onclick = () => {
+        fetch(link)
+        .then(res => res.json())
+        .then(obj => createTable(parent, obj))
+      }
+      container.append(button)
+    }
+
+    let table = document.createElement('table')
+    table.style.marginBottom = '15px'
+    table.border = '1'
+
+    for (let [key, value] of Object.entries(object)) {
+        let row = document.createElement('tr')
+        let cell = document.createElement('td')
+        cell.style.fontWeight= 'bold'
+        cell.innerText = key
+        let cell2 = document.createElement('td')
+        if (Array.isArray(value)) {
+          for (let link of value) {
+            makeButton(cell2, link)
+          }
+        } else if (typeof value === 'string' && value.startsWith('https://swapi.dev/api/')) {
+          makeButton(cell2, value)
+        } else {
+          cell2.innerText = value
+        }
+        row.append(cell, cell2)
+        table.append(row)
+    }
+
+    parent.append(table)
+    return object
+    })(document.querySelector('body'), luke)
+  )
+  .then(obj => console.log(obj))
+
+//myfetch
+function myfetch(url) {
+  return new Promise(function (resolve, reject) {
+      const xhr = new XMLHttpRequest()
+      xhr.open('GET', url, true)
+      xhr.responseType = 'json'
+      xhr.send()
+      xhr.onload = () => {
+        if (xhr.status !== 200) {
+          reject(xhr.status)
+        } else {
+          resolve(xhr.response)
+        }
+      }
+  })
+}
+
+myfetch('https://swapi.dev/api/people/1/')
+  .then(luke => console.log(luke))
+  .catch(error => console.log('Ашипка! status: ' + error))
+
+//race
+let delay = (ms) => new Promise((fulfill, reject) => {
+  setTimeout(() => fulfill(ms), ms)
+})
+
+Promise.race([delay(200), myfetch('https://swapi.dev/api/people/4/')]).then(res => console.log(res))
+
+
+
+