//-------------------------------------------------fetch basic------------------------------------------------------------------------- // fetch('https://swapi.dev/api/people/1/') // .then(res => res.json()) // .then(luke => console.log(luke)) function pushToTable(element, name) { const url = "http://swapi.dev/api/"; function addButton(elem, value) { let button = document.createElement("button"); button.append(value); elem.append(button); button.onclick = () => { table2.removeChild(table2.firstChild); fetch(value) .then((res) => res.json()) .then((luke) => pushToTable(table2, luke)); } } let table = document.createElement("table"); table.setAttribute("border", "2"); element.append(table); for (let key in name) { let tr = document.createElement("tr"); table.append(tr); let th = document.createElement("th"); tr.append(th); th.append(key); let td = document.createElement("td"); tr.append(td); if (typeof name[key] == "string") { if (name[key].startsWith(url)) { addButton(td, name[key]); } else { td.append(name[key]) } } else { if (Array.isArray(name[key])) { for (let key2 of name[key]) { if (key2.startsWith(url)) { addButton(td, key2) } else { td.append(key2) } } } } } } fetch("https://swapi.dev/api/people/1/") .then((res) => res.json()) .then((luke) => { pushToTable(table1, luke); pushToTable(table2, luke); }); //-------------------------------------------------myfetch------------------------------------------------------------------------- let myfetch = function (url) { return new Promise(function (resolve, rejected) { let request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "json"; request.onload = function () { if (this.status == 200) { resolve(this.response) } else { rejected(new Error(`Error: ${this.status}: ${this.statusText}`)) } } request.send(null) }) } myfetch("https://swapi.dev/api/people/1/").then( (luke) => console.log(JSON.stringify(luke)), (error) => alert(error) ); //-------------------------------------------------race------------------------------------------------------------------------- btn.onclick = function () { function delay(milliSecondsnds) { return new Promise((resolved) => setTimeout(() => resolved(`Delay ${milliSecondsnds}`), milliSecondsnds)) } Promise.race([delay(+num.value), myfetch("https://swapi.dev/api/people/1/") ]).then((resolved) => { race.value = resolved; console.log(resolved); }) } const num = document.getElementById("num");