constructor()

in src/core/Deferred.js [30:117]


  constructor(executable = () => {}, onResolve, onReject, onCancel) {
    if (typeof executable !== 'function') {
      throw new Error(
        `Cannot create new Deferred. Executable must be a function.`
      );
    }

    if (typeof onResolve !== 'undefined' && typeof onResolve !== 'function') {
      throw new Error(
        `Cannot create new Deferred. OnResolve must be a function.`
      );
    }

    if (typeof onReject !== 'undefined' && typeof onReject !== 'function') {
      throw new Error(
        `Cannot create new Deferred. OnReject must be a function.`
      );
    }

    if (typeof onCancel !== 'undefined' && typeof onCancel !== 'function') {
      throw new Error(
        `Cannot create new Deferred. OnCancel must be a function.`
      );
    }

    let res;
    let rej;
    let cancel;
    const status = {
      resolved: false,
      rejected: false,
      canceled: false,
      pending: true,
    };

    super((resolve, reject) => {
      // Store the resolver
      res = value => {
        if (status.pending) {
          status.resolved = true;
          status.pending = false;

          if (typeof onResolve === 'function') {
            value = onResolve(value);
          }

          return resolve(value);
        }
      };

      // Store the rejecter
      rej = value => {
        if (status.pending) {
          status.rejected = true;
          status.pending = false;

          if (typeof onReject === 'function') {
            value = onReject(value);
          }

          return reject(value);
        }
      };

      // Store the canceler
      cancel = value => {
        if (status.pending) {
          status.canceled = true;
          status.pending = false;

          if (typeof onCancel === 'function') {
            value = onCancel(value);
          }

          return resolve(value);
        }
      };

      // Run the executable with custom resolver and rejecter
      executable(res, rej, cancel);
    });

    this._status = status;
    this._resolve = res;
    this._reject = rej;
    this._cancel = cancel;
    this._executable = executable;
  }