Created
March 17, 2019 14:37
-
-
Save zheeeng/dadaa774395f8a4f504b99e04ab91e92 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 race = async function * (size, taskIter) { | |
const queue = [] | |
// enqueue | |
while (queue.length < size) { | |
const nextTask = taskIter.next() | |
if (!nextTask.done) { | |
queue.push(nextTask.value()) | |
} else { | |
break | |
} | |
} | |
while (queue.length) { | |
await Promise.race(queue) | |
const winnerIndex = await Promise.race(queue.map((item, i) => item.then(_ => i))) | |
const winner = queue[winnerIndex] | |
const nextTask = taskIter.next() | |
if (!nextTask.done) { | |
// replace and enqueue | |
queue.splice(queue.findIndex(qt => qt === winner), 1, nextTask.value()) | |
} else { | |
queue.splice(queue.findIndex(qt => qt === winner), 1) | |
} | |
yield winner | |
} | |
} | |
const limitExec = async (tasks, size) => { | |
const taskIter = tasks[Symbol.iterator]() | |
const result = [] | |
for await (let winnerValue of race(size, taskIter)) { | |
result.push(winnerValue) | |
} | |
return result | |
} | |
const testTasks = Array.from( | |
{ length: 12 }, | |
(_, index) => () => new Promise(resolve => setTimeout(resolve, Math.random() * 5000, index)) | |
) | |
limitExec(testTasks, 3).then(console.log) |
Author
zheeeng
commented
May 5, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment