Advertisement
Pijomir

Untitled

Feb 28th, 2024
618
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const stopIdElement = document.getElementById('stopId');
  2. const stopNameElement = document.getElementById('stopName');
  3. const bussesInfoELement = document.getElementById('buses');
  4.  
  5. async function getInfo() {
  6.     const stopId = stopIdElement.value;
  7.     const url = `http://localhost:3030/jsonstore/bus/businfo/${stopId}`;
  8.  
  9.     try {
  10.         const response = await fetch(url);
  11.         if (!response.ok) {
  12.             const errorMessage = await response.json();
  13.             throw errorMessage;
  14.         }
  15.  
  16.         const data = await response.json();
  17.         stopNameElement.textContent = data.name;
  18.         bussesInfoELement.replaceChildren(...Object.entries(data.buses).map(line => createListItem(line[0], line[1])));
  19.         stopIdElement.value = '';
  20.     } catch {
  21.         stopNameElement.textContent = 'Error';
  22.         stopIdElement.value = '';
  23.         bussesInfoELement.innerHTML = '';
  24.     }
  25.  
  26.     function createListItem(busId, time) {
  27.         const item = document.createElement('li');
  28.         item.textContent = `Bus ${busId} arrives in ${time} minutes`;
  29.         return item;
  30.     }
  31. }
  32.  
  33.  
  34.  
  35. // then-catch:
  36. // function getInfo() {
  37. //     const stopIdElement = document.getElementById('stopId');
  38. //     const stopNameElement = document.getElementById('stopName');
  39. //     const bussesInfoELement = document.getElementById('buses');
  40. //     const stopId = stopIdElement.value;
  41. //     const url = `http://localhost:3030/jsonstore/bus/businfo/${stopId}`;
  42.  
  43. //     fetch(url)
  44. //         .then(onHeaders)
  45. //         .then(onSuccess)
  46. //         .catch(onError);
  47.  
  48. //     function onHeaders(response) {
  49. //         if (!response.ok) {
  50. //             throw 'Error';
  51. //         }
  52.  
  53. //         return response.json();
  54. //     }
  55.  
  56. //     function onSuccess(data) {
  57. //         stopNameElement.textContent = data.name;
  58. //         bussesInfoELement.replaceChildren(...Object.entries(data.buses).map(line => createListItem(line[0], line[1])));
  59. //         stopIdElement.value = '';
  60. //     }
  61.  
  62. //     function onError(error) {
  63. //         stopNameElement.textContent = 'Error';
  64. //     }
  65.  
  66. //     function createListItem(busId, time) {
  67. //         const item = document.createElement('li');
  68. //         item.textContent = `Bus ${busId} arrives in ${time} minutes`;
  69. //         return item;
  70. //     }
  71. // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement