This repository has been archived by the owner on Jun 4, 2023. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
90 additions
and
29 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
export class Queue { | ||
private queue: { | ||
promise: () => Promise<any>; | ||
reject: any; | ||
resolve: any; | ||
}[] = []; | ||
private pendingPromise = false; | ||
|
||
public enqueue<T>(promise: () => Promise<T>): Promise<T> { | ||
return new Promise((resolve, reject) => { | ||
this.queue.push({ | ||
promise, | ||
resolve, | ||
reject, | ||
}); | ||
|
||
this.dequeue(); | ||
}); | ||
} | ||
|
||
public dequeue() { | ||
if (this.pendingPromise) { | ||
return false; | ||
} | ||
const item = this.queue.shift(); | ||
if (!item) { | ||
return false; | ||
} | ||
try { | ||
this.pendingPromise = true; | ||
item | ||
.promise() | ||
.then(value => { | ||
this.pendingPromise = false; | ||
item.resolve(value); | ||
this.dequeue(); | ||
}) | ||
.catch(err => { | ||
this.pendingPromise = false; | ||
item.reject(err); | ||
this.dequeue(); | ||
}); | ||
} catch (err) { | ||
this.pendingPromise = false; | ||
item.reject(err); | ||
this.dequeue(); | ||
} | ||
return true; | ||
} | ||
} |