Created
December 26, 2023 17:04
-
-
Save kevinrodriguez-io/b8af6464c98d7964983591e069a16467 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class QueueNode<T> { | |
public promise: () => Promise<T>; | |
public next: QueueNode<T> | null; | |
public finished: boolean; | |
constructor(promise: () => Promise<T>) { | |
this.promise = promise; | |
} | |
} | |
class AsyncQueue { | |
private first: QueueNode<any>; | |
private last: QueueNode<any>; | |
constructor(initialNode: QueueNode<any>) { | |
this.first = initialNode; | |
this.last = initialNode; | |
} | |
public add<T>(item: QueueNode<T>) { | |
if (this.first === this.last) { | |
this.first.next = item; | |
this.last = item; | |
} else { | |
this.last.next = item; | |
this.last = item; | |
} | |
} | |
public async run(onFullfill: (result: any) => void) { | |
let current: QueueNode<any> | null = this.first; | |
while (current !== null) { | |
const result = await current.promise(); | |
onFullfill(result); | |
current = current.next; | |
if (current?.next === null) { | |
this.first = current; | |
this.last = current; | |
} | |
} | |
} | |
} | |
const task1 = () => | |
new Promise((resolve) => setTimeout(() => resolve(1), 1000)); | |
const task2 = () => | |
new Promise((resolve) => setTimeout(() => resolve(2), 2000)); | |
const task3 = () => | |
new Promise((resolve) => setTimeout(() => resolve(3), 3000)); | |
const node1 = new QueueNode(task1); | |
const node2 = new QueueNode(task2); | |
const node3 = new QueueNode(task3); | |
const queue = new AsyncQueue(node1); | |
queue.add(node2); | |
queue.add(node3); | |
queue.run((result) => console.log(result)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment