Last active
April 19, 2021 20:48
-
-
Save onhate/d5c4dc306d4761bb1574cb9184c15af6 to your computer and use it in GitHub Desktop.
Queue Executor in Vanilla Javascript / Typescript
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
export const waitForMillis = async (millis: number) => { | |
return new Promise(resolve => setTimeout(resolve, millis)); | |
}; | |
export const executor = (concurrency = 100) => { | |
let workers = 0; | |
let index = 0; | |
let queue = []; | |
const waitFor = async () => { | |
do { | |
if (workers === 0 && index === queue.length) return true; | |
await waitForMillis(250); | |
} while (true); | |
}; | |
const execute = (...jobs: (() => Promise<any>)[]) => { | |
queue.push(...jobs); | |
const finished = index => result => { | |
queue[index] = result; | |
workers--; | |
tick(); | |
}; | |
const tick = () => { | |
if (workers < concurrency && index < queue.length) { | |
const resolver = queue[index]; | |
resolver().then(finished(index)).catch(finished(index)); | |
++index && ++workers; | |
tick(); | |
} | |
// cleanup queue | |
if (workers === 0 && index === queue.length) { | |
index = 0; | |
queue.length = 0; | |
} | |
}; | |
tick(); | |
}; | |
return { | |
execute, | |
waitFor | |
}; | |
}; |
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
import { executor } from './executor'; | |
const globalExecutor = executor(2); // max of 2 parallel executions | |
globalExecutor.execute(functionThatResolvesPromise); | |
globalExecutor.execute(anotherFunctionThatResolvesPromise); | |
globalExecutor.execute(functionThatWillWaitForExecution); | |
await globalExecutor.waitFor(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment