123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- //fetch basic, fetch improved
- // let table = document.createElement('table');
- // let tr = document.createElement('tr');
- // let th = document.createElement('th');
- // let th2 = document.createElement('th');
- // document.body.appendChild(table);
- // table.appendChild(tr);
- // tr.appendChild(th);
- // tr.appendChild(th2);
- // th.innerHTML = 'Key';
- // th2.innerHTML = 'Value';
- // let luke = new Promise(function (resolve, reject) {
- // resolve(fetch('https://swapi.dev/api/people/1/'));
- // })
- // luke.then(resolve => resolve.json())
- // .then(luke => createTable(luke, table));
- // function createTable(json, dom){
- // let url = 'https://swapi.dev/api/'
- // console.log(json)
- // for(let [key, value] of Object.entries(json)){
- // let tr = document.createElement('tr');
- // let tdKey = document.createElement('td');
- // let tdVal = document.createElement('td');
- // tdKey.innerHTML = key;
- // if(value.includes(url)){
- // tdVal.appendChild(createBtn(value, tdVal));
- // } else if(typeof (value) === 'object') {
- // value.forEach((el) =>{
- // tdVal.appendChild(createBtn(el, tdVal));
- // })
- // } else {
- // tdVal.innerHTML = value;
- // }
- // dom.appendChild(tr);
- // tr.appendChild(tdKey);
- // tr.appendChild(tdVal);
- // }
- // }
- // function createBtn(fetchLink, tdV){
- // let btn = document.createElement('button');
- // btn.innerHTML = 'btn';
- // btn.onclick = function(){
- // fetch(fetchLink)
- // .then(resolve => resolve.json())
- // .then(subFetch => createTable(subFetch, tdV))
- // }
- // return btn;
- // }
- //myfetch
- function myfetch(url) {
- return p1 = new Promise(function (resolve, reject) {
- let xhr = new XMLHttpRequest();
- xhr.open('GET', url);
- xhr.onload = function() {
- if(this.status == 200) {
- resolve(JSON.parse(xhr.response));
- } else {
- reject (this.status);
- }
- };
- xhr.send();
- });
- }
- myfetch('https://swapi.dev/api/people/1/')
- .then(luke => console.log(luke));
- //race
- function delay(ms, url) {
- return p2 = new Promise(function (resolve, reject) {
- let xhr = new XMLHttpRequest();
- xhr.open('GET', url);
- xhr.onload = function() {
- if(this.status == 200) {
- resolve(JSON.parse(xhr.response));
- } else {
- reject (this.status);
- }
- };
- xhr.send();
- });
- }
- delay(3000, 'https://swapi.dev/api/people/1/')
- .then(() => console.log('выполнилось через 3 секунды'));
- Promise.race([p1, p2]).then((value) => {
- console.log(value);
- });
|