-
-
Save jupemara/202dfb833bb33184695f3042eac0a434 to your computer and use it in GitHub Desktop.
pure nodejs Promise queue
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 TaskQueue { | |
constructor (con) { | |
this.con = con; | |
this.running = 0; | |
this.queue = []; | |
} | |
pushTask (task) { | |
this.queue.push(task); | |
this.next(); | |
} | |
next() { | |
while (this.running < this.con && this.queue.length) { | |
const task = this.queue.shift(); | |
console.log('started task'); | |
task().then(() => { | |
this.running--; | |
this.next(); | |
}); | |
this.running++; | |
} | |
} | |
} | |
(() => { | |
const t1 = () => { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
console.log(1); | |
resolve(); | |
}, Math.random() * (1000 - 50) + 50); | |
}); | |
}; | |
const t2 = () => { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
console.log(2); | |
resolve(); | |
}, Math.random() * (3000 - 500) + 500); | |
}); | |
}; | |
const q = new TaskQueue(2); | |
q.pushTask(t1); | |
q.pushTask(t1); | |
q.pushTask(t2); | |
q.pushTask(t2); | |
q.pushTask(t1); | |
q.pushTask(t2); | |
console.log('started'); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment