Browse Source

errors catching addded.(to be tested)

miskson 3 years ago
parent
commit
8635f2a7e1
1 changed files with 40 additions and 10 deletions
  1. 40 10
      hw11-promise/script.js

+ 40 - 10
hw11-promise/script.js

@@ -37,14 +37,28 @@ function drawObjTable(parent, obj) {
                 i++;
                 console.log('current', item)
                 if (typeof item === 'string' && /^(https:\/\/|http:\/\/)/.test(item)) {
-                    let btn = createBtn(i)
+                    let btn = createBtn('Loading...')
 
+                    
                     fetch(item)
-                    .then(res => res.json())
-                    .then(obj => {
-                        btn.innerText = obj[Object.keys(obj)[0]]
-                        btn.onclick = () => { drawObjTable(container, obj) }
-                    })
+                        .then((res) => {
+                            if(res.ok) {
+                                return res.json()
+                            } else {
+                                throw new Error()
+                            }
+                        
+                        })
+                        .then(obj => {
+                            btn.innerText = obj[Object.keys(obj)[0]]
+                            btn.onclick = () => { drawObjTable(container, obj) }
+                        })
+                        .catch((e) => {
+                            console.warn('something bad happened. ',e)    
+                            btn = document.createElement('a')
+                            btn.innerText =  item
+                            btn.href = item
+                        })
 
                     tdValue.append(btn)
                 } else {
@@ -53,7 +67,17 @@ function drawObjTable(parent, obj) {
             }
         } else if (typeof obj[key] === 'string' && /^(https:\/\/|http:\/\/)/.test(obj[key])) {
             let btn = createBtn(key)
-            btn.onclick = () => request_N_redraw(obj[key])
+            try {
+                fetch(obj[key])
+                    .then(res => res.json())
+                    .then(obj => {
+                        btn.innerText = obj[Object.keys(obj)[0]]
+                        btn.onclick = () => { drawObjTable(container, obj) }
+                    })
+            } catch(e) {
+                console.warn('something bad happened. ',e)
+            }
+
             tdValue.append(btn)
         } else {
             tdValue.innerText = obj[key]
@@ -69,8 +93,14 @@ let container = document.createElement('div')
 document.body.append(container)
 
 fetch('https://swapi.dev/api/people/1/')
-    .then(res => res.json())
+    .then((res) => {
+        if(res.ok) {
+            return res.json()
+        } else {
+            throw new Error()
+        }
+    })
     .then(luke => {
-        console.log(luke)
         drawObjTable(container, luke)
-    })
+    })
+    .catch((e) => console.warn('something bad happpened ', e))