Async Then Work Introduction
A function to pool and manage multiple web workers after multiple async actions
Installation
yarn add @procore/labs-async-then-work
Usage
someWorker.worker.js
/* eslint-disable no-restricted-globals */
// Trivial worker that just sums some numbers
self.onmessage = ({ data }) => {
self.postMessage(
data.reduce((acc, item) => (acc + item), 0)
);
self.close();
};
WorkerWrapper.js
import {
bundleWorkerAndResolve,
bundleAsyncActionAndWorkerBundles,
poolAsyncAndWorkerBundles,
} from '@procore/labs-async-then-work';
import { fetchDataForWorkerToProcess } from './fetchDataForWorkerToProcess'
import * as SomeWorker from './someWorker.worker';
const wrapper => (resolveToState) => {
// Callback is called when worker returns data
// 'workerKey' comes from next level, but easiest
// to assume it is the const name
const someWorkerResolveBundle = bundleWorkerAndResolve(
new SomeWorker(),
({ workerKey, data }) => resolveToState(workerKey, data)
);
// Fetches data for one or more workers to do work on.
// worker and resolver bundles are passed in as obj to allow
// name to be used as key later in resolve callback
const someAsyncBundle = bundleAsyncActionAndWorkerBundles(
() => fetchDataForWorkerToProcess(),
{ someWorkerResolveBundle }
);
// Pools, manages, and calls all async actions and workers
poolAsyncAndWorkerBundles({ someAsyncBundle });
}