main.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //fetch basic/improved
  2. fetch('https://swapi.dev/api/people/1/')
  3. .then(res => res.json())
  4. .then(luke => (function createTable(parent, object) {
  5. let makeButton = (container, link) => {
  6. let button = document.createElement('button')
  7. button.innerText = 'create table'
  8. button.dataset.link = link
  9. button.onclick = () => {
  10. fetch(link)
  11. .then(res => res.json())
  12. .then(obj => createTable(parent, obj))
  13. }
  14. container.append(button)
  15. }
  16. let table = document.createElement('table')
  17. table.style.marginBottom = '15px'
  18. table.border = '1'
  19. for (let [key, value] of Object.entries(object)) {
  20. let row = document.createElement('tr')
  21. let cell = document.createElement('td')
  22. cell.style.fontWeight= 'bold'
  23. cell.innerText = key
  24. let cell2 = document.createElement('td')
  25. if (Array.isArray(value)) {
  26. for (let link of value) {
  27. makeButton(cell2, link)
  28. }
  29. } else if (typeof value === 'string' && value.startsWith('https://swapi.dev/api/')) {
  30. makeButton(cell2, value)
  31. } else {
  32. cell2.innerText = value
  33. }
  34. row.append(cell, cell2)
  35. table.append(row)
  36. }
  37. parent.append(table)
  38. return object
  39. })(document.querySelector('body'), luke)
  40. )
  41. .then(obj => console.log(obj))
  42. //myfetch
  43. function myfetch(url) {
  44. return new Promise(function (resolve, reject) {
  45. const xhr = new XMLHttpRequest()
  46. xhr.open('GET', url, true)
  47. xhr.responseType = 'json'
  48. xhr.send()
  49. xhr.onload = () => {
  50. if (xhr.status !== 200) {
  51. reject(xhr.status)
  52. } else {
  53. resolve(xhr.response)
  54. }
  55. }
  56. })
  57. }
  58. myfetch('https://swapi.dev/api/people/1/')
  59. .then(luke => console.log(luke))
  60. .catch(error => console.log('Ашипка! status: ' + error))
  61. //race
  62. let delay = (ms) => new Promise((fulfill, reject) => {
  63. setTimeout(() => fulfill(ms), ms)
  64. })
  65. Promise.race([delay(200), myfetch('https://swapi.dev/api/people/4/')]).then(res => console.log(res))