ijob
TypeScript icon, indicating that this package has built-in type declarations

0.0.10 • Public • Published

ijob

Helper for creating cancellable promise-returning functions.

Create simple job

import job from 'ijob';
 
async function doSomething() {}
async function cleanup() {}
function processResult() {}
 
const myJob = job(async ({onCancel, isCancelled}) => {
  onCancel(cleanup);
  const result = await doSomething();
  if (!isCancelled()) {
    processResult(result);
  }
});
 
myJob.onCancel(() => console.log('job cancelled'));
myJob.onSuccess(() => console.log('job succeeded'));
myJob.onError(() => console.log('job failed'));
myJob.onDone(() => console.log('job done'));
// job.cancel();

Support (Async) Generator

import job from 'ijob';
let count = 0;
const Increase = () => count++;
const Delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
 
job(function* () {
  for (let i = 0; i < 1000; i++) {
    yield [Delay, 100]; // delay in 100ms
    yield [Increase];
  }
});

Perform the latest job

import job from 'ijob';
const callServerApi = () => {};
const renderProductList = () => {};
const SearchProducts = job.latest(({isCancelled}) => async (term) => {
  const products = await callServerApi(term);
  if (!isCancelled()) {
    renderProductList(products);
  }
});

Waiting for function execution

import job from 'ijob';
 
const f1 = job.func(async () => {
  await delay(1000);
  return 1;
});
 
const f2 = job.func(async () => {
  await delay(500);
  return 2;
});
 
const result1 = await job.any([f1, f2]); // => result1 = 2
const result2 = await job.all([f1, f2]); // => result2 = [1, 2]

Dependents (0)

Package Sidebar

Install

npm i ijob

Weekly Downloads

0

Version

0.0.10

License

ISC

Unpacked Size

40.4 kB

Total Files

10

Last publish

Collaborators

  • linq2js