Skip to content

Instantly share code, notes, and snippets.

@arc279
Created April 25, 2024 02:10
Show Gist options
  • Save arc279/7877d41bc6465e1b845848d414a61652 to your computer and use it in GitHub Desktop.
Save arc279/7877d41bc6465e1b845848d414a61652 to your computer and use it in GitHub Desktop.
javascript で並列 worker
// 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