script.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. function createTable(element,information){
  2. for(let i in information){
  3. let tr = document.createElement('tr');
  4. let th = document.createElement('th');
  5. let td = document.createElement('td');
  6. th.innerText=i;
  7. td.innerText = information[i];
  8. tr.appendChild(th);
  9. tr.appendChild(td);
  10. element.appendChild(tr);
  11. };
  12. };
  13. fetch('https://swapi.dev/api/starships/9/')
  14. .then(res => res.json())
  15. .then(luke =>createTable(assignment,luke))
  16. function createImproved(element,information){
  17. function clickBtn(btn,el){
  18. btn.onclick=()=>{
  19. fetch(el)
  20. .then(res => res.json())
  21. .then(luke =>createImproved(improved,luke))
  22. };
  23. };
  24. for(let i in information){
  25. let tr = document.createElement('tr');
  26. let th = document.createElement('th');
  27. let td = document.createElement('td');
  28. th.innerText=i;
  29. tr.appendChild(th);
  30. if (typeof information[i]==='string'&&information[i].indexOf("http://swapi.dev/api/")===0){
  31. let btn = document.createElement('button');
  32. td.appendChild(btn);
  33. btn.classList.add('linkBtn');
  34. btn.innerText='link';
  35. clickBtn(btn,information[i]);
  36. } else if(typeof information[i]==='object'){
  37. for(let key of information[i]){
  38. let btn = document.createElement('button');
  39. td.appendChild(btn)
  40. btn.innerText='oppen array';
  41. clickBtn(btn,key);
  42. }
  43. } else {
  44. td.innerText =information[i];
  45. }
  46. tr.appendChild(td);
  47. element.appendChild(tr);
  48. };
  49. };
  50. fetch('https://swapi.dev/api/starships/9/')
  51. .then(res => res.json())
  52. .then(luke =>createImproved(improved,luke))
  53. function mFetch(url){
  54. return new Promise(function (res, rej){
  55. const xxx = new XMLHttpRequest();
  56. xxx.open("GET", url,true);
  57. xxx.onload = () =>{
  58. if (xxx.status != 200){
  59. rej(xxx.response);
  60. }else {
  61. res(JSON.parse(xxx.responseText));
  62. };
  63. };
  64. xxx.onerror = () => reject(xhr.statusText);
  65. xxx.send();
  66. });
  67. };
  68. mFetch('https://swapi.dev/api/starships/9/')
  69. .then(luke => console.log(luke))
  70. const promise1 = new Promise(function(resolve,reject){
  71. mFetch('https://swapi.dev/api/starships/9/')
  72. .then(() =>resolve('promise1') )
  73. });
  74. const promise2 = ms => new Promise(ok => setTimeout(() => ok("promise2"), ms));
  75. Promise.race([promise1, promise2(120)]).then(function(value) {
  76. console.log(value);
  77. });