|
@@ -0,0 +1,58 @@
|
|
|
+// 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((resolve, reject) => {
|
|
|
+ setTimeout(() => {
|
|
|
+ fetch('https://swapi.dev/api/people/1/')
|
|
|
+ .then(res => res.json())
|
|
|
+ .then(luke => console.log(luke))
|
|
|
+ }, Math.random() * 1000);
|
|
|
+});
|
|
|
+let delay = new Promise((resolve, reject) => {
|
|
|
+ setTimeout(() => resolve('delay'), Math.random() * 1000);
|
|
|
+});
|
|
|
+Promise.race([mfetch, delay]).then((res) => {
|
|
|
+ console.log(res);
|
|
|
+});
|