1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- //fetch basic/improved
- fetch('https://swapi.dev/api/people/1/')
- .then(res => res.json())
- .then(luke => (function createTable(parent, object) {
- let makeButton = (container, link) => {
- let button = document.createElement('button')
- button.innerText = 'create table'
- button.dataset.link = link
- button.onclick = () => {
- fetch(link)
- .then(res => res.json())
- .then(obj => createTable(parent, obj))
- }
- container.append(button)
- }
- let table = document.createElement('table')
- table.style.marginBottom = '15px'
- table.border = '1'
- for (let [key, value] of Object.entries(object)) {
- let row = document.createElement('tr')
- let cell = document.createElement('td')
- cell.style.fontWeight= 'bold'
- cell.innerText = key
- let cell2 = document.createElement('td')
- if (Array.isArray(value)) {
- for (let link of value) {
- makeButton(cell2, link)
- }
- } else if (typeof value === 'string' && value.startsWith('https://swapi.dev/api/')) {
- makeButton(cell2, value)
- } else {
- cell2.innerText = value
- }
- row.append(cell, cell2)
- table.append(row)
- }
- parent.append(table)
- return object
- })(document.querySelector('body'), luke)
- )
- .then(obj => console.log(obj))
- //myfetch
- function myfetch(url) {
- return new Promise(function (resolve, reject) {
- const xhr = new XMLHttpRequest()
- xhr.open('GET', url, true)
- xhr.responseType = 'json'
- xhr.send()
- xhr.onload = () => {
- if (xhr.status !== 200) {
- reject(xhr.status)
- } else {
- resolve(xhr.response)
- }
- }
- })
- }
- myfetch('https://swapi.dev/api/people/1/')
- .then(luke => console.log(luke))
- .catch(error => console.log('Ашипка! status: ' + error))
- //race
- let delay = (ms) => new Promise((fulfill, reject) => {
- setTimeout(() => fulfill(ms), ms)
- })
- Promise.race([delay(200), myfetch('https://swapi.dev/api/people/4/')]).then(res => console.log(res))
-
|