cancellation

A method for making async operations cancellable

cancellation

A method for making async operations cancellable

$ component install ForbesLindesay/cancellation

NPM:

$ npm install cancellation

Returns a new CancellationTokenSource:

var tokenSource = require('cancellation');
var source = tokenSource();
callAsyncOperation(arg1, arg2, arg3, source.token);
setTimeout(function () {
  source.cancel('Operation timed out');
}, 1000);

Returns an 'empty' CancellationToken (one that will never be cancelled).

var tokenSource = require('cancellation');
function asyncOperation(arg1arg2arg3cancellationToken) {
  cancellationToken = cancellationToken || tokenSource.empty;
 
  //Continue with function knowing there is a cancellation token 
}

Returns true if the token has been cancelled:

//In ES6 
function asyncOperation(cancellationToken) {
  return spawn(function* () {
    while(!cancellationToken.isCancelled()) {
      yield NextAsyncOp();
    }
  })
}

Throws the rejection reason if the token has been cancelled:

//In ES6 
function asyncOperation(cancellationToken) {
  return spawn(function* () {
    while(true) {
      cancellationToken.throwIfCancelled()
      yield NextAsyncOp();
    }
  })
}

Calls cb when the cancellation token is cancelled (this is probably currently the most useful of these methods).

function get(urlcancellationToken) {
  var def = defer();
  
  var req = request(url, function (errres) {
    if (err) def.reject(err);
    else def.resolve(res);
  });
 
  cancellationToken
    .onCancelled(function (reason) {
      def.reject(reason);
      req.abort();
    });
 
  return def.promise;
}

MIT