123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- // fetch basic
- // fetch improved
- fetch('https://swapi.dev/api/people/1/')
- .then(res => res.json())
- .then(luke => createHero(document.body, luke))
- function createHero(parent, data) {
- let table = document.createElement('table')
- table.style.border = '2px solid #808080'
- table.style.borderCollapse = 'collapse'
- table.style.background = '#FFFAF0'
- parent.append(table)
- for (let key in data) {
- let tr = document.createElement('tr')
- table.append(tr)
- let th = document.createElement('th')
- th.style.border = '2px solid #808080'
- tr.append(th)
- th.append(key)
-
- let td = document.createElement('td')
- td.style.border = '2px solid #808080'
- tr.append(td)
- let btn = function(parent, link) {
- button = document.createElement('button')
- button.style.background = '#AFEEEE'
- button.style.color = '#1E90FF'
- button.append(link)
- parent.append(button)
- button.onclick = () => {
- fetch(link)
- .then(res => res.json())
- .then(luke => createHero(document.body, luke))
- }
- }
- if (data[key] instanceof Array) {
- for (let arr of data[key]) {
- if (arr.startsWith('https://swapi.dev/api/')) {
- btn(td, arr)
- }
- else td.append(data[key])
- }
- }
- else {
- if (typeof data[key] === 'string' && data[key].startsWith('https://swapi.dev/api/')) {
- btn(td, data[key])
- }
- else td.append(data[key])
- }
- }
- }
- // myfetch
- // example1
- function myfetch(url) {
- return new Promise(function (resolve, reject) {
- const xhr = new XMLHttpRequest()
- xhr.open('GET', url)
- xhr.onload = () => {
- if (xhr.status != 200) {
- reject(`Error: ${xhr.statusText}`)
- return
- }
- resolve(JSON.parse(xhr.response))
- }
- xhr.onerror = function() {
- reject('Error')
- }
- xhr.send()
- })
- }
- myfetch('https://swapi.dev/api/people/1/')
- .then(luke => console.log(luke)) // вывод в консоль
- // or
- // example2
- 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) {
- reject(console.log('Error' + this.statusText))
- }
- else {
- resolve(JSON.parse(xhr.responseText))
- }
- }
-
- xhr.send()
- })
- }
- myfetch('https://swapi.dev/api/people/1/')
- .then(createHero => console.log(createHero)) // вывод в консоль
- // myfetch('https://swapi.dev/api/people/1/')
- // .then(json => createHero(document.body, json)) // для отрисовки на странице
- // race
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
- Promise.race([myfetch('https://swapi.dev/api/people/1/'),delay(100)]).then(res => console.log(res))
|