bada-terminal / src /utils /queue-manager.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
1.68 kB
class ConcurrencyQueue {
constructor(maxConcurrency = 2) {
this.maxConcurrency = maxConcurrency;
this.runningCount = 0;
this.queue = [];
}
enqueue(taskFn, { signal } = {}) {
return new Promise((resolve, reject) => {
// ์ทจ์†Œํ•œ ๋Œ€๊ธฐ ํ•ญ๋ชฉ๋งŒ ํšŒ์ˆ˜ํ•œ๋‹ค. ์‹คํ–‰ ์ค‘์ธ ๋‹ค๋ฅธ ์ž‘์—…์ด๋‚˜ ์ „์ฒด ํ๋ฅผ ๋น„์šฐ์ง€ ์•Š๋Š”๋‹ค.
const cleanup = () => signal?.removeEventListener('abort', abort);
const entry = { taskFn, resolve, reject, cleanup };
const abort = () => {
const index = this.queue.indexOf(entry);
if (index >= 0) this.queue.splice(index, 1);
cleanup();
reject(new Error('Queued request cancelled'));
};
if (signal?.aborted) { abort(); return; }
signal?.addEventListener('abort', abort, { once: true });
this.queue.push(entry);
this.next();
});
}
next() {
if (this.runningCount >= this.maxConcurrency) {
return;
}
if (this.queue.length === 0) {
return;
}
const { taskFn, resolve, reject, cleanup } = this.queue.shift();
cleanup();
this.runningCount++;
Promise.resolve()
.then(() => taskFn())
.then(result => {
this.runningCount = Math.max(0, this.runningCount - 1);
resolve(result);
this.next();
})
.catch(err => {
this.runningCount = Math.max(0, this.runningCount - 1);
reject(err);
this.next();
});
}
cancelAll() {
const pending = this.queue.splice(0);
for (const { reject, cleanup } of pending) {
cleanup();
reject(new Error('Queue cancelled'));
}
}
}
module.exports = { ConcurrencyQueue };