1.0.2 • Published 1 year ago

@lpezet/ts-cancellation v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

MKay Diary

A non-supported implemetation of Cancellation in Typescript.

NPM Version Linux Build Windows Build Test Coverage Known Vulnerabilities

Example taken from rbuckton/CancellationToken.md:

public fetchAsync(url, cancellationToken = CancellationToken.default) {
  return new Promise((resolve, reject) => {
    // throw (reject) if cancellation has already been requested.
    cancellationToken.throwIfCanceled();

    // alternatively:
    //
    //   // if cancellation has been requested, reject the Promise with the reason for cancellation.
    //   if (cancellationToken.canceled) {
    //     reject(cancellationToken.reason);
    //     return; 
    //   }
    //
    // or even:
    //
    //   // register the reject handler of the Promise to receive the cancellation signal. If the source is already
    //   // canceled, this will call the reject handler immediately.
    //   cancellationToken.register(reject); 
    //   if (cancellationToken.canceled) {
    //     return;
    //   }

    var xhr = new XMLHttpRequest();

    // save a callback to abort the xhr when cancellation is requested
    var oncancel = (reason: any) => {
      // abort the request
      xhr.abort();
      
      // reject the promise
      reject(reason);
    }

    // wait for the remote resource
    xhr.onload = event => {
      // async operation completed, stop waiting for cancellation
      registration.unregister();

      // resolve the promise
      resolve(event);
    }

    xhr.onerror = event => {
      // async operation failed, stop waiting for cancellation
      cancellationToken.unregister();

      // reject the promise
      reject(event);
    }
    
    // register the callback to execut when cancellation is requested
    var registration = cancellationToken.register(oncancel);

    // begin the async operation
    xhr.open('GET', url, /*async*/ true);
    xhr.send(null);
  });
}

Table of Contents

Installation

npm install @lpezet/ts-cancellation

References

https://github.com/microsoft/referencesource/blob/master/Microsoft.Bcl/System.Threading.Tasks.v1.5/System/Threading/CancellationTokenRegistration.cs

https://gist.github.com/bakerface/492c631c6aa23e915bde9243252b52f4

https://gist.github.com/rbuckton/256c4e929f4a097e2c16

https://github.com/rbuckton/asyncjs/blob/master/lib/cancellation.ts

License

MIT

Publishing

To publish next version of @lpezet/ts-cancellation, run the following:

npm version patch
git push --tags origin main
npm run build-prod
npm publish --access public
1.0.2

1 year ago