123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- /* fetch basic & fetch improved*/
- let result = document.body
- fetch('https://swapi.py4e.com/api/people/1/')
- .then(res => res.json())
- .then(luke => createTable(result, luke));
- function createTable(result, JSON) {
- let table = document.createElement("table");
- function createCol(title, value) {
- let tr = document.createElement("tr");
- let td = document.createElement("td");
- let td1 = document.createElement("td");
- td.innerHTML = title;
- if (typeof value === "object") {
-
- if (Array.isArray(value)) {
- value.forEach(elem => {
- td1.appendChild(elem)
- }
- );
- }
- else {
- td1.appendChild(value)
- }
- } else {
- td1.innerHTML = value;
- }
- table.append(tr);
- tr.append(td, td1);
- }
- for (let [key, value] of Object.entries(JSON)) {
- createCol(key, link(value));
- }
- result.append(table);
- table.border = 1;
- }
- function link(str, container) {
- if (typeof str === 'string') {
- if (str.includes('https://')) {
- let btn = document.createElement('button')
- btn.innerHTML = 'Go'
- btn.onclick = () => {
- fetch(str).then(r => r.json())
- .then(r => createTable(btn.parentElement, r))
- }
- return btn
- } else {
- return str
- }
- }
- else if (typeof str === 'object') {
- let arrStr = str.map(item => {
- if (item.includes('https://')) {
- let btn = document.createElement('button')
- btn.innerHTML = 'Go'
- btn.onclick = () => {
- fetch(item).then(r => r.json())
- .then(r => createTable(btn.parentElement, r))
- }
- return btn
- } else {
- return item
- }
- })
- return arrStr
- }
- else {
- return str
- }
- }
- /* 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.onreadystatechange = function() {
- if (xhr.readyState != 4) {
- return;
- }
- if (xhr.status == 200){
- resolve(JSON.parse(xhr.responseText));
- } else {
- reject('err')
- }
- }
- xhr.open('GET', url , true);
- xhr.send(null);
- })
- }
- /* race */
- let luke1 = new Promise((resolve, reject) => {
- fetch('https://swapi.dev/api/people/1/')
- .then(res => res.json())
- .then(luke => console.log(luke))
- });
-
- let delay = new Promise((resolve, reject) => {
- setTimeout(resolve, Math.random() * 1000, 'delay');
- });
-
- Promise.race([luke1, delay]).then((x) => {
- console.log(x);
- });
|