0.0.1-alpha.0 • Published 3 years ago

@procore/labs-async-then-work v0.0.1-alpha.0

Weekly downloads
-
License
SEE LICENSE IN LI...
Repository
github
Last release
3 years ago

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 });
}