1. class QueueGuard {
  2. constructor(queue) {
  3. this.queue = queue;
  4. }
  5. /**
  6. * Executes a function on the queue, handling potential errors.
  7. * @param {function} task - The function to execute.
  8. * @param {number} [maxRetries=3] - Maximum number of retries.
  9. * @param {number} [retryDelay=1000] - Delay between retries in milliseconds.
  10. * @returns {Promise<any>} - A promise that resolves with the result of the task or rejects if all retries fail.
  11. */
  12. async executeTask(task, maxRetries = 3, retryDelay = 1000) {
  13. let retries = 0;
  14. while (retries < maxRetries) {
  15. try {
  16. const result = await task();
  17. return result; // Success, return the result
  18. } catch (error) {
  19. retries++;
  20. console.warn(`Task failed (attempt ${retries}/${maxRetries}):`, error);
  21. if (retries < maxRetries) {
  22. await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
  23. } else {
  24. throw error; // Re-throw the error if all retries failed
  25. }
  26. }
  27. }
  28. throw new Error("Max retries reached without success."); //Should not reach here, but good to have.
  29. }
  30. /**
  31. * Adds a task to the queue, guarded by the QueueGuard.
  32. * @param {function} task - The function to add to the queue.
  33. */
  34. addGuardedTask(task) {
  35. this.queue.push(async () => {
  36. try {
  37. return await this.executeTask(task);
  38. } catch (error) {
  39. console.error("Task failed within guarded execution:", error);
  40. throw error; // Re-throw to propagate the error if needed.
  41. }
  42. });
  43. }
  44. }
  45. //Example Usage:
  46. //const myQueue = [];
  47. //const queueGuard = new QueueGuard(myQueue);
  48. //async function myTask() {
  49. // // Simulate an exploratory task that might fail
  50. // return new Promise((resolve, reject) => {
  51. // setTimeout(() => {
  52. // if (Math.random() < 0.5) {
  53. // resolve("Task completed successfully!");
  54. // } else {
  55. // reject(new Error("Task failed intentionally!"));
  56. // }
  57. // }, 500);
  58. // });
  59. //}
  60. //queueGuard.addGuardedTask(myTask);
  61. //async function processQueue() {
  62. // while(myQueue.length > 0){
  63. // const task = myQueue.shift();
  64. // try {
  65. // const result = await task();
  66. // console.log("Queue Result:", result);
  67. // } catch(error){
  68. // console.error("Queue Error: ", error);
  69. // }
  70. // }
  71. //}
  72. //processQueue();

Add your comment