Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Pool {
- constructor (queues, options) {
- options = options || {};
- this._polling = options.polling || 100;
- this._qq = [];
- for (let i = 0; i < queues; i++) {
- this._qq.push(new Queue(i + 1));
- }
- }
- addTask (weight, task) {
- if (typeof(weight) === "function") {
- task = weight;
- weight = 1;
- }
- let queue = this._qq[0];
- if (this._qq.length > 1) {
- for (const q of this._qq) {
- if (queue.weight === 0) break;
- if (q.weight < queue.weight) queue = q;
- };
- };
- queue.add(weight, task);
- }
- addBatch (tasks) {
- for (const task of tasks) {
- this.addTask(task);
- }
- }
- wait (timeout = null) {
- const start = new Date();
- return new Promise((resolve, reject) => {
- const timerId = setInterval(() => {
- let q, isFinished = true;
- for (q of this._qq) {
- if (q.weight > 0) {
- isFinished = false;
- break;
- }
- }
- if (isFinished) {
- clearInterval(timerId);
- resolve();
- return;
- }
- if (timeout != null && (new Date() - start > timeout)) {
- clearInterval(timerId);
- for (q of this._qq) {
- q.close();
- }
- reject(Error(`Timeout ${timeout} ms has expired`));
- return;
- }
- }, this._polling);
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement