script.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // task fetchbasic
  2. // &&
  3. // task fetch improved
  4. const wrapper = document.getElementById("wrapper");
  5. fetch("https://swapi.dev/api/people/1/")
  6. .then((res) => res.json())
  7. .then((luke) => creatTable(luke, wrapper));
  8. function creatTable(data, dom) {
  9. let table = document.createElement("table");
  10. dom.appendChild(table);
  11. let html = "";
  12. for (let key in data) {
  13. html += `<tr>`;
  14. html += `<td>${key}</td>`;
  15. if (Array.isArray(data[key])) {
  16. html += `<td>`;
  17. data[key].forEach((element) => {
  18. html += `<button>${element}</button>`;
  19. });
  20. html += `</td>`;
  21. } else {
  22. if (isNaN(data[key]) && data[key].includes("https://")) {
  23. html += `<td><button>${data[key]}</button></td>`;
  24. } else {
  25. html += `<td>${data[key]}</td>`;
  26. html += `</tr>`;
  27. }
  28. }
  29. }
  30. table.innerHTML = html;
  31. document.querySelectorAll("button").forEach((btn) => {
  32. btn.addEventListener("click", openNewTable);
  33. });
  34. }
  35. function openNewTable(event) {
  36. const url = event.target.innerText;
  37. fetch(url)
  38. .then((res) => res.json())
  39. .then((json) => creatTable(json, wrapper));
  40. }
  41. // Task myfetch
  42. const apiUrl = "https://swapi.dev/api/people/1/";
  43. function myfetch(url) {
  44. return new Promise(function (resolve, reject) {
  45. const xhr = new XMLHttpRequest();
  46. xhr.open("get", url, true);
  47. xhr.send();
  48. xhr.onload = function () {
  49. if (xhr.status === 200) {
  50. resolve(JSON.parse(xhr.response));
  51. } else {
  52. reject(xhr.status);
  53. }
  54. };
  55. });
  56. }
  57. const response = myfetch(apiUrl);
  58. response.then(
  59. (data) => {
  60. console.log(data);
  61. },
  62. (data) => {
  63. console.log(data);
  64. }
  65. );
  66. // Task race
  67. const delay = setTimeout(() => {
  68. console.log('Done waiting');
  69. }, Math.floor(Math.random() * 7000));
  70. Promise.race([delay, response])