Created
March 28, 2020 16:01
-
-
Save Yama-Tomo/6213088f5a56371849955266650916ad to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// ジェネレータを使うとイテレートしているリストを増やしたり逆に減らしたりすることができるのでキュー管理と並列実行をテーマとしたサンプル | |
const pararell = 2 | |
const queues = [1, 2, 3, 4] | |
const runner = (taskManager) => | |
new Promise(r => { | |
const queue = taskManager.next() | |
if (queue.done) { | |
r() | |
return | |
} | |
// hevy process | |
setTimeout(() => { | |
console.log(queue.value) | |
if (queue.value == 3) { | |
console.log(` ==> add queue at ${queue.value}`) | |
queues.push(...[5, 6, 7, 8, 9, 10]) | |
} | |
if (queue.value == 6) { | |
console.log(` ==> reduce queue at ${queue.value}`) | |
queues.splice(2) | |
} | |
r() | |
}, 2000) | |
}) | |
async function main() { | |
const taskManager = (function* (queues) { | |
while(queues.length) { | |
yield queues.shift() | |
} | |
})(queues) | |
while(queues.length) { | |
await Promise.all(Array.from({ length: pararell }, (_, i) => runner(taskManager))) | |
} | |
console.log('done') | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment