Created
July 11, 2021 06:02
-
-
Save zbinlin/541ccb9cf6e9c07f98c7605648c7ea34 to your computer and use it in GitHub Desktop.
Work 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
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