1. /**
  2. * Loads resources from an array of URLs, with fallback logic.
  3. * @param {Array<string>} urls An array of URLs to load resources from.
  4. * @param {number} retries The number of retries if a resource fails to load.
  5. * @returns {Promise<Array<any>>} A promise that resolves with an array of loaded resources.
  6. * Returns an empty array if all resources fail to load after retries.
  7. */
  8. async function loadResources(urls, retries = 3) {
  9. const loadedResources = [];
  10. for (const url of urls) {
  11. let resource;
  12. let success = false;
  13. for (let i = 0; i < retries; i++) {
  14. try {
  15. resource = await fetch(url); // Attempt to fetch the resource
  16. if (!resource.ok) {
  17. throw new Error(`HTTP error! Status: ${resource.status}`);
  18. }
  19. resource = await resource.json(); // Attempt to parse as JSON
  20. success = true;
  21. break; // Exit retry loop on success
  22. } catch (error) {
  23. console.error(`Failed to load ${url} (attempt ${i + 1}):`, error);
  24. if (i === retries - 1) {
  25. console.warn(`Failed to load ${url} after ${retries} retries.`);
  26. break; // Exit retry loop after all retries fail
  27. }
  28. }
  29. }
  30. if (success) {
  31. loadedResources.push(resource);
  32. }
  33. }
  34. return loadedResources;
  35. }

Add your comment