All files / lib/cancel CancelToken.js

84.21% Statements 16/19
50% Branches 3/6
100% Functions 6/6
84.21% Lines 16/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58    1x                 1x         1x 1x     1x 1x 1x         1x 1x             1x 1x                 1x   1x 1x   1x           1x  
'use strict';
 
var Cancel = require('./Cancel');
 
/**
 * A `CancelToken` is an object that can be used to request cancellation of an operation.
 *
 * @class
 * @param {Function} executor The executor function.
 */
function CancelToken(executor) {
  Iif (typeof executor !== 'function') {
    throw new TypeError('executor must be a function.');
  }
 
  var resolvePromise;
  this.promise = new Promise(function promiseExecutor(resolve) {
    resolvePromise = resolve;
  });
 
  var token = this;
  executor(function cancel(message) {
    Iif (token.reason) {
      // Cancellation has already been requested
      return;
    }
 
    token.reason = new Cancel(message);
    resolvePromise(token.reason);
  });
}
 
/**
 * Throws a `Cancel` if cancellation has been requested.
 */
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  Iif (this.reason) {
    throw this.reason;
  }
};
 
/**
 * Returns an object that contains a new `CancelToken` and a function that, when called,
 * cancels the `CancelToken`.
 */
CancelToken.source = function source() {
  var cancel;
  var token = new CancelToken(function executor(c) {
    cancel = c;
  });
  return {
    token: token,
    cancel: cancel
  };
};
 
module.exports = CancelToken;