0.0.10 • Published 4 years ago

ijob v0.0.10

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

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]
0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.5

4 years ago

0.0.6

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago