1. class TokenQueue {
  2. constructor() {
  3. this.queue = [];
  4. this.isRunning = false;
  5. }
  6. enqueue(task) {
  7. this.queue.push(task);
  8. }
  9. start() {
  10. if (this.isRunning) {
  11. return; // Prevent concurrent runs
  12. }
  13. this.isRunning = true;
  14. this.runNext();
  15. }
  16. runNext() {
  17. if (this.queue.length === 0) {
  18. this.isRunning = false;
  19. return;
  20. }
  21. const task = this.queue.shift();
  22. // Simulate token authentication (replace with your actual logic)
  23. const token = task.authenticate();
  24. // Execute the task with the token
  25. task.execute(token);
  26. this.runNext(); // Process the next task
  27. }
  28. }
  29. // Example usage:
  30. // Define a task
  31. class AuthenticationTask {
  32. authenticate() {
  33. // Simulate authentication - replace with your real authentication logic
  34. return "validToken_" + Date.now();
  35. }
  36. execute(token) {
  37. console.log(`Executing task with token: ${token}`);
  38. // Perform the experiment task using the token.
  39. console.log("Task completed.");
  40. }
  41. }
  42. // Create a queue
  43. const queue = new TokenQueue();
  44. // Create tasks and enqueue them
  45. const task1 = new AuthenticationTask();
  46. const task2 = new AuthenticationTask();
  47. const task3 = new AuthenticationTask();
  48. queue.enqueue(task1);
  49. queue.enqueue(task2);
  50. queue.enqueue(task3);
  51. // Start the queue
  52. queue.start();

Add your comment