Js-HW12.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. fetch('https://swapi.dev/api/people/1/')
  2. .then(res => res.json())
  3. .then(luke => renderTable(document.body, luke))
  4. function renderTable(parent, obj) {
  5. let $table = document.createElement('table')
  6. for(let key in obj) {
  7. let $tr = document.createElement('tr')
  8. let $td = document.createElement('td')
  9. let $td2 = document.createElement('td')
  10. if(Array.isArray(obj[key])) {
  11. for(let item of obj[key]) {
  12. let newTable = document.createElement('table')
  13. let newTr = document.createElement('tr')
  14. let newTd = document.createElement('td')
  15. linkChecker(item, newTd)
  16. newTr.append(newTd)
  17. newTable.append(newTr)
  18. $td2.append(newTable)
  19. }
  20. } else {
  21. linkChecker(obj[key], $td2)
  22. }
  23. $td.innerHTML = key
  24. $tr.append($td, $td2)
  25. $table.appendChild($tr)
  26. }
  27. parent.appendChild($table)
  28. }
  29. function linkChecker(str, container) {
  30. if(typeof str === 'string') {
  31. if(str.includes('https://swapi.dev/api/')) {
  32. let btn = document.createElement('button')
  33. btn.innerHTML = 'Show'
  34. btn.onclick = () => {
  35. fetch(str).then(r => r.json())
  36. .then(r => renderTable(container, r))
  37. // .then(r => console.log(r))
  38. }
  39. container.append(btn)
  40. } else {
  41. container.innerHTML = str
  42. }
  43. }
  44. }
  45. function myFetch(url){
  46. return new Promise(function (resolve, reject){
  47. const xhr = new XMLHttpRequest()
  48. xhr.open('get', url)
  49. xhr.onload = function () {
  50. if (xhr.status >= 200 && xhr.status < 300) {
  51. resolve(xhr.response);
  52. } else {
  53. reject(() => alert('something went wrong'));
  54. }
  55. xhr.send();
  56. }});
  57. }
  58. myFetch('https://swapi.dev/api/peope/4/')
  59. .then(res => console.log(res))
  60. function delay(ms) {
  61. return setTimeout(() => console.log('delay worked'), ms)
  62. }
  63. Promise.race([myFetch('https://swapi.dev/api/peope/4/'), delay(300)]).then(val => console.log(val))
  64. Promise.race([myFetch('https://swapi.dev/api/peope/1/'), delay(200)]).then(val => console.log(val))