main.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //fetch basic, fetch improved
  2. // let table = document.createElement('table');
  3. // let tr = document.createElement('tr');
  4. // let th = document.createElement('th');
  5. // let th2 = document.createElement('th');
  6. // document.body.appendChild(table);
  7. // table.appendChild(tr);
  8. // tr.appendChild(th);
  9. // tr.appendChild(th2);
  10. // th.innerHTML = 'Key';
  11. // th2.innerHTML = 'Value';
  12. // let luke = new Promise(function (resolve, reject) {
  13. // resolve(fetch('https://swapi.dev/api/people/1/'));
  14. // })
  15. // luke.then(resolve => resolve.json())
  16. // .then(luke => createTable(luke, table));
  17. // function createTable(json, dom){
  18. // let url = 'https://swapi.dev/api/'
  19. // console.log(json)
  20. // for(let [key, value] of Object.entries(json)){
  21. // let tr = document.createElement('tr');
  22. // let tdKey = document.createElement('td');
  23. // let tdVal = document.createElement('td');
  24. // tdKey.innerHTML = key;
  25. // if(value.includes(url)){
  26. // tdVal.appendChild(createBtn(value, tdVal));
  27. // } else if(typeof (value) === 'object') {
  28. // value.forEach((el) =>{
  29. // tdVal.appendChild(createBtn(el, tdVal));
  30. // })
  31. // } else {
  32. // tdVal.innerHTML = value;
  33. // }
  34. // dom.appendChild(tr);
  35. // tr.appendChild(tdKey);
  36. // tr.appendChild(tdVal);
  37. // }
  38. // }
  39. // function createBtn(fetchLink, tdV){
  40. // let btn = document.createElement('button');
  41. // btn.innerHTML = 'btn';
  42. // btn.onclick = function(){
  43. // fetch(fetchLink)
  44. // .then(resolve => resolve.json())
  45. // .then(subFetch => createTable(subFetch, tdV))
  46. // }
  47. // return btn;
  48. // }
  49. //myfetch
  50. function myfetch(url) {
  51. return p1 = new Promise(function (resolve, reject) {
  52. let xhr = new XMLHttpRequest();
  53. xhr.open('GET', url);
  54. xhr.onload = function() {
  55. if(this.status == 200) {
  56. resolve(JSON.parse(xhr.response));
  57. } else {
  58. reject (this.status);
  59. }
  60. };
  61. xhr.send();
  62. });
  63. }
  64. myfetch('https://swapi.dev/api/people/1/')
  65. .then(luke => console.log(luke));
  66. //race
  67. function delay(ms, url) {
  68. return p2 = new Promise(function (resolve, reject) {
  69. let xhr = new XMLHttpRequest();
  70. xhr.open('GET', url);
  71. xhr.onload = function() {
  72. if(this.status == 200) {
  73. resolve(JSON.parse(xhr.response));
  74. } else {
  75. reject (this.status);
  76. }
  77. };
  78. xhr.send();
  79. });
  80. }
  81. delay(3000, 'https://swapi.dev/api/people/1/')
  82. .then(() => console.log('выполнилось через 3 секунды'));
  83. Promise.race([p1, p2]).then((value) => {
  84. console.log(value);
  85. });