Created
April 25, 2024 02:10
-
-
Save arc279/7877d41bc6465e1b845848d414a61652 to your computer and use it in GitHub Desktop.
javascript で並列 worker
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
// cf. https://maximorlov.com/parallel-tasks-with-pure-javascript/ | |
import { setTimeout } from 'node:timers/promises'; | |
async function doWork(iterator, i) { | |
for await (const value of iterator) { | |
await setTimeout(1000); | |
console.log(`worker ${i}: ${value}`); | |
} | |
console.log(`worker ${i} finish`) | |
} | |
const ar = [...Array(20)].map((_, i) => i) | |
const iterator = ar.values(); | |
const workers = new Array(3).fill(iterator).map(doWork); | |
await Promise.allSettled(workers); | |
console.log('Done!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment