swapi_dom.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // SWAPI Links
  2. function fetchGet(url) {
  3. return fetch(url)
  4. .then((response) => {
  5. if (response.ok) {
  6. return response.json(); // json() returns Promise!
  7. } else {
  8. return Promise.reject(new Error(response.statusText));
  9. }
  10. });
  11. }
  12. function swapiLinks(url) {
  13. let obj;
  14. return fetchGet(url)
  15. .then(response => {
  16. console.log(response);
  17. obj = response;
  18. const linkPromises = [];
  19. Object.values(obj).forEach(value => {
  20. if (typeof value == 'string' && value.includes('https://swapi.dev/api/')) {
  21. linkPromises.push(fetchGet(value));
  22. } else if (Array.isArray(value)) {
  23. value.forEach((el) => {
  24. if (typeof el == 'string' && el.includes('https://swapi.dev/api/')) {
  25. linkPromises.push(fetchGet(el));
  26. }
  27. });
  28. }
  29. });
  30. return Promise.all(linkPromises);
  31. }).then(linkResponses => {
  32. Object.keys(obj).forEach(key => {
  33. if (typeof obj[key] == 'string' && obj[key].includes('https://swapi.dev/api/')) {
  34. obj[key] = linkResponses.shift();
  35. } else if (Array.isArray(obj[key])) {
  36. obj[key].forEach((el, i) => {
  37. if (typeof el == 'string' && el.includes('https://swapi.dev/api/')) {
  38. obj[key][i] = linkResponses.shift();
  39. }
  40. });
  41. }
  42. });
  43. return Promise.resolve(obj);
  44. })
  45. .catch((error) => {
  46. return Promise.reject(error);
  47. });
  48. }
  49. swapiLinks("https://swapi.dev/api/people/20/")
  50. .then(yodaWithLinks => {
  51. console.log(JSON.stringify(yodaWithLinks, null, 4));
  52. })
  53. .catch((error) => {
  54. console.log(error);
  55. });
  56. // domEventPromise
  57. {
  58. function domEventPromise(element, eventName) {
  59. function executor(resolve) {
  60. let fn = (event) => {
  61. resolve(event);
  62. element.removeEventListener(eventName, fn);
  63. };
  64. element.addEventListener(eventName, fn);
  65. }
  66. return new Promise(executor)
  67. }
  68. domEventPromise(document.getElementById('click'), 'click').then(e => console.log('event click happens', e))
  69. }