// Javascript Async: Promise Homework // fetch basic fetch('https://swapi.dev/api/people/1/') .then((res) => res.json()) .then((luke) => { basic(document.body, luke) }); function basic(dom, json) { const table = document.createElement("table"); dom.appendChild(table); for (let key in json) { const tr = document.createElement("tr") const td = document.createElement("td"); tr.innerText = key; td.innerText = json[key]; tr.appendChild(td); table.appendChild(tr) } } // myfetch myfetch('https://swapi.dev/api/people/1/') .then(luke => console.log(luke)) function myfetch(url) { return new Promise(function (resolve, reject) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = function () { if (xhr.readyState != 4) { return; } if (xhr.status == 200) { resolve(JSON.parse(xhr.responseText)); } else { reject('err') } } xhr.send(); }) } // race let mfetch = new Promise(() => { setTimeout(() => { fetch('https://swapi.dev/api/people/1/') .then(res => res.json()) .then(luke => console.log(luke)) }, Math.random() * 1000); }); let delay = ms => new Promise(ok => setTimeout(() => ok(console.log('delay')), Math.random() * ms)); await Promise.race([mfetch, delay(1000)]);