main.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //fetch basic + improved
  2. fetch('https://swapi.dev/api/people/1/')
  3. .then(res => res.json())
  4. .then(luke => swapiTable(document.body, luke))
  5. function swapiTable(parent, data) {
  6. let table = document.createElement("table")
  7. table.border = 1
  8. table.style.borderColor = 'purple'
  9. parent.append(table)
  10. for (let key in data) {
  11. let tr = document.createElement("tr")
  12. table.append(tr)
  13. let th = document.createElement("th")
  14. tr.append(th)
  15. th.append(key)
  16. let td = document.createElement("td")
  17. tr.append(td)
  18. let btn = function(parent, link) {
  19. button = document.createElement("button")
  20. button.append(link)
  21. button.style.background = "#8B008B"
  22. button.style.color = 'white'
  23. parent.append(button)
  24. button.onclick = () => {
  25. fetch(link)
  26. .then(res => res.json())
  27. .then(luke => swapiTable(document.body, luke))
  28. }
  29. }
  30. if (data[key] instanceof Array) {
  31. for (let arr of data[key]) {
  32. if (arr.startsWith("https://swapi.dev/api/")) {
  33. btn(td, arr)
  34. } else td.append(data[key])
  35. }
  36. }else { if (data[key].startsWith("https://swapi.dev/api/")) {
  37. btn(td, data[key])
  38. }else td.append(data[key])
  39. }
  40. }
  41. }
  42. //myfetch
  43. function myfetch(url){
  44. return new Promise(function (resolve, reject){
  45. const xhr = new XMLHttpRequest()
  46. xhr.open('GET', url)
  47. xhr.onload = () => {
  48. if (xhr.status != 200) {
  49. reject(`Ошибка: ${xhr.statusText}`)
  50. return
  51. }
  52. resolve(JSON.parse(xhr.response))
  53. }
  54. xhr.onerror = function() {
  55. reject("Error")
  56. }
  57. xhr.send()
  58. })
  59. }
  60. myfetch('https://swapi.dev/api/people/1/')
  61. .then(luke => console.log(luke))
  62. //race
  63. const delay = new Promise((resolve, reject) => {
  64. setTimeout(resolve, Math.random() * 100, 'delay');
  65. });
  66. Promise.race([delay , myfetch('https://swapi.dev/api/people/1/')]).then((value) => {
  67. console.log(value)
  68. })