Skip to content

Instantly share code, notes, and snippets.

@zbinlin
Created July 11, 2021 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zbinlin/541ccb9cf6e9c07f98c7605648c7ea34 to your computer and use it in GitHub Desktop.
Save zbinlin/541ccb9cf6e9c07f98c7605648c7ea34 to your computer and use it in GitHub Desktop.
Work Queue
import { promisify } from 'util';
const sleep = promisify(setTimeout);
class WorkQueue {
#gen;
constructor() {
const gen = WorkQueue.#processor();
gen.next(); // ignore first call
this.#gen = gen;
}
static async *#processor() {
let result;
while (true) {
const [process, payload] = yield result;
result = await process(payload);
}
}
async enqueue(payload, callback) {
const result = await this.#gen.next([callback, payload]);
return result.value;
}
}
const wq = new WorkQueue();
async function processJob1() {
console.log('3');
console.log(await wq.enqueue(3, async (payload) => {
await sleep(1000);
return payload ** 2;
}));
}
async function processJob2() {
console.log('2');
console.log(await wq.enqueue(2, async (payload) => {
await sleep(500);
return payload ** 4;
}));
}
async function processJob3() {
console.log('throw error');
try {
await wq.enqueue(undefined, () => {
throw new Error('err');
});
} catch (ex) {
console.log(ex.message);
}
}
processJob1();
processJob2();
processJob3();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment