12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- // SWAPI Links
- function fetchGet(url) {
- return fetch(url)
- .then((response) => {
- if (response.ok) {
- return response.json(); // json() returns Promise!
- } else {
- return Promise.reject(new Error(response.statusText));
- }
- });
- }
- function swapiLinks(url) {
- let obj;
- return fetchGet(url)
- .then(response => {
- console.log(response);
- obj = response;
- const linkPromises = [];
- Object.values(obj).forEach(value => {
- if (typeof value == 'string' && value.includes('https://swapi.dev/api/')) {
- linkPromises.push(fetchGet(value));
- } else if (Array.isArray(value)) {
- value.forEach((el) => {
- if (typeof el == 'string' && el.includes('https://swapi.dev/api/')) {
- linkPromises.push(fetchGet(el));
- }
- });
- }
- });
- return Promise.all(linkPromises);
- }).then(linkResponses => {
- Object.keys(obj).forEach(key => {
- if (typeof obj[key] == 'string' && obj[key].includes('https://swapi.dev/api/')) {
- obj[key] = linkResponses.shift();
- } else if (Array.isArray(obj[key])) {
- obj[key].forEach((el, i) => {
- if (typeof el == 'string' && el.includes('https://swapi.dev/api/')) {
- obj[key][i] = linkResponses.shift();
- }
- });
- }
- });
- return Promise.resolve(obj);
- })
- .catch((error) => {
- return Promise.reject(error);
- });
- }
- swapiLinks("https://swapi.dev/api/people/20/")
- .then(yodaWithLinks => {
- console.log(JSON.stringify(yodaWithLinks, null, 4));
- })
- .catch((error) => {
- console.log(error);
- });
- // domEventPromise
- {
- function domEventPromise(element, eventName) {
- function executor(resolve) {
- let fn = (event) => {
- resolve(event);
- element.removeEventListener(eventName, fn);
- };
- element.addEventListener(eventName, fn);
- }
- return new Promise(executor)
- }
- domEventPromise(document.getElementById('click'), 'click').then(e => console.log('event click happens', e))
- }
|