Worker Pools in TypeScript
Our example demonstrates how to implement a worker pool using asynchronous functions and promises.
In this example, we’re using asynchronous functions and promises to simulate concurrent behavior. Here’s a breakdown of what’s happening:
We define a
worker
function that takes an ID, a jobs array, and a results array. It processes each job, simulates work with a 1-second delay, and adds the result to the results array.In the
main
function, we create our jobs and results arrays.We start three worker functions, each processing the same jobs array and writing to the same results array.
We use
Promise.all
to wait for all workers to complete before logging the results.
To run this program, save it as worker-pools.ts
and use ts-node
(assuming you have TypeScript and ts-node installed):
This program demonstrates how to distribute work across multiple asynchronous functions. Despite doing about 5 seconds of total work, the program only takes about 2 seconds to complete because there are 3 workers operating concurrently.
Note that while this example simulates concurrent behavior, JavaScript (and by extension, TypeScript) is single-threaded. For true parallelism in JavaScript environments, you would need to use Web Workers in a browser context or Worker Threads in Node.js.