Skip to content

fxmaxvl/cancellable.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cancellable.js

Simple tool for creating cancellable promise-returning/async functions.

How to install

yarn add cancellable.js ## or npm install cancellable.js

How to use

import Cancellable from 'cancellable.js';

// use case: with single cancellable function

const doSomeAsyncStaff = () => new Promise(res => setTimeout(res, 1000));
const doSomeSyncStaff  = () => null;

const doSomeAsyncStaffCancellable = Cancellable.create(doSomeAsyncStaff);

async function useSingleAsyncStaff() {
    try {
        await doSomeAsyncStaffCancellable();
        doSomeSyncStaff();
    } catch (error) {
        if (Cancellable.isCanceled(error)) {
            // handle cancellation case or do nothing
           
            return;
        }
        
        // your regular error handling logic
    }
}

useSingleAsyncStaff();

Cancellable.cancel(doSomeAsyncStaffCancellable);

// use case: with multiple cancellable functions

const doSomeAsyncStaff      = () => new Promise(res => setTimeout(res, 1000));
const doSomeOtherAsyncStaff = () => new Promise(res => setTimeout(res, 2000));
const doSomeSyncStaff       = () => null;

const doSomeAsyncStaffCancellable      = Cancellable.create(doSomeAsyncStaff);
const doSomeOtherAsyncStaffCancellable = Cancellable.create(doSomeOtherAsyncStaff);

async function useMultipleAsyncStaff() {
    try {
        await doSomeAsyncStaffCancellable();
        await doSomeOtherAsyncStaffCancellable();
        doSomeSyncStaff();
    } catch (error) {
        if (Cancellable.isCanceled(error)) {
            // handle cancellation case or do nothing
           
            return;
        }
        
        // your regular error handling logic
    }
}

useMultipleAsyncStaff();

// it is possible to cancel several cancellable functions at onсe
Cancellable.cancel(doSomeAsyncStaffCancellable, doSomeOtherAsyncStaffCancellable);

About

Simple tool for creating cancellable promise-returning/async functions.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published