All files / lib/timers promises.js

99.13% Statements 228/230
96.72% Branches 59/61
88.88% Functions 8/9
99.13% Lines 228/230

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 2312x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 2x 170x 170x 170x 4x 4x 4x 4x 4x 4x 166x 166x 166x 170x 6x 6x 170x 5x 5x 5x 5x 5x 5x 155x 155x 155x 170x 3x 3x 152x 152x 152x 152x 152x 4x 4x 4x 4x 152x 170x 4x 4x 170x 170x 2x 48x 48x 4x 4x 4x 4x 4x 4x 44x 44x 44x 48x 6x 6x 48x 5x 5x 5x 5x 5x 5x 33x 33x 33x 48x 2x 2x 31x 31x 31x 31x 31x 3x 3x 3x 3x 3x 31x 48x 3x 3x 48x 48x 2x 74x 74x 74x 74x 74x 74x 74x 74x 56x 56x 56x 56x 56x 56x 56x 436x 436x 127x 127x 127x 56x 56x 74x 6x 4x 4x 1x 1x 1x 1x 1x 6x 6x 6x 56x 74x 129x 129x 127x 128x 134x 83x 129x 74x 74x 10x 10x 10x 74x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 66x 2x 2x  
'use strict';
 
const {
  FunctionPrototypeBind,
  Promise,
  PromiseReject,
  ReflectConstruct,
  SafePromisePrototypeFinally,
  Symbol,
} = primordials;
 
const {
  Timeout,
  Immediate,
  insert
} = require('internal/timers');
const {
  clearImmediate,
  clearInterval,
  clearTimeout,
} = require('timers');
 
const {
  AbortError,
  codes: {
    ERR_ILLEGAL_CONSTRUCTOR,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_THIS,
  }
} = require('internal/errors');
 
const {
  validateAbortSignal,
  validateBoolean,
  validateObject,
} = require('internal/validators');
 
const {
  kEmptyObject,
} = require('internal/util');
 
const kScheduler = Symbol('kScheduler');
 
function cancelListenerHandler(clear, reject, signal) {
  if (!this._destroyed) {
    clear(this);
    reject(new AbortError(undefined, { cause: signal?.reason }));
  }
}
 
function setTimeout(after, value, options = kEmptyObject) {
  const args = value !== undefined ? [value] : value;
  if (options == null || typeof options !== 'object') {
    return PromiseReject(
      new ERR_INVALID_ARG_TYPE(
        'options',
        'Object',
        options));
  }
  const { signal, ref = true } = options;
  try {
    validateAbortSignal(signal, 'options.signal');
  } catch (err) {
    return PromiseReject(err);
  }
  if (typeof ref !== 'boolean') {
    return PromiseReject(
      new ERR_INVALID_ARG_TYPE(
        'options.ref',
        'boolean',
        ref));
  }
  // TODO(@jasnell): If a decision is made that this cannot be backported
  // to 12.x, then this can be converted to use optional chaining to
  // simplify the check.
  if (signal && signal.aborted) {
    return PromiseReject(new AbortError(undefined, { cause: signal.reason }));
  }
  let oncancel;
  const ret = new Promise((resolve, reject) => {
    const timeout = new Timeout(resolve, after, args, false, ref);
    insert(timeout, timeout._idleTimeout);
    if (signal) {
      oncancel = FunctionPrototypeBind(cancelListenerHandler,
                                       timeout, clearTimeout, reject, signal);
      signal.addEventListener('abort', oncancel);
    }
  });
  return oncancel !== undefined ?
    SafePromisePrototypeFinally(
      ret,
      () => signal.removeEventListener('abort', oncancel)) : ret;
}
 
function setImmediate(value, options = kEmptyObject) {
  if (options == null || typeof options !== 'object') {
    return PromiseReject(
      new ERR_INVALID_ARG_TYPE(
        'options',
        'Object',
        options));
  }
  const { signal, ref = true } = options;
  try {
    validateAbortSignal(signal, 'options.signal');
  } catch (err) {
    return PromiseReject(err);
  }
  if (typeof ref !== 'boolean') {
    return PromiseReject(
      new ERR_INVALID_ARG_TYPE(
        'options.ref',
        'boolean',
        ref));
  }
  // TODO(@jasnell): If a decision is made that this cannot be backported
  // to 12.x, then this can be converted to use optional chaining to
  // simplify the check.
  if (signal && signal.aborted) {
    return PromiseReject(new AbortError(undefined, { cause: signal.reason }));
  }
  let oncancel;
  const ret = new Promise((resolve, reject) => {
    const immediate = new Immediate(resolve, [value]);
    if (!ref) immediate.unref();
    if (signal) {
      oncancel = FunctionPrototypeBind(cancelListenerHandler,
                                       immediate, clearImmediate, reject,
                                       signal);
      signal.addEventListener('abort', oncancel);
    }
  });
  return oncancel !== undefined ?
    SafePromisePrototypeFinally(
      ret,
      () => signal.removeEventListener('abort', oncancel)) : ret;
}
 
async function* setInterval(after, value, options = kEmptyObject) {
  validateObject(options, 'options');
  const { signal, ref = true } = options;
  validateAbortSignal(signal, 'options.signal');
  validateBoolean(ref, 'options.ref');
 
  if (signal?.aborted)
    throw new AbortError(undefined, { cause: signal?.reason });
 
  let onCancel;
  let interval;
  try {
    let notYielded = 0;
    let callback;
    interval = new Timeout(() => {
      notYielded++;
      if (callback) {
        callback();
        callback = undefined;
      }
    }, after, undefined, true, ref);
    insert(interval, interval._idleTimeout);
    if (signal) {
      onCancel = () => {
        clearInterval(interval);
        if (callback) {
          callback(
            PromiseReject(
              new AbortError(undefined, { cause: signal.reason })));
          callback = undefined;
        }
      };
      signal.addEventListener('abort', onCancel, { once: true });
    }
 
    while (!signal?.aborted) {
      if (notYielded === 0) {
        await new Promise((resolve) => callback = resolve);
      }
      for (; notYielded > 0; notYielded--) {
        yield value;
      }
    }
    throw new AbortError(undefined, { cause: signal?.reason });
  } finally {
    clearInterval(interval);
    signal?.removeEventListener('abort', onCancel);
  }
}
 
// TODO(@jasnell): Scheduler is an API currently being discussed by WICG
// for Web Platform standardization: https://github.com/WICG/scheduling-apis
// The scheduler.yield() and scheduler.wait() methods correspond roughly to
// the awaitable setTimeout and setImmediate implementations here. This api
// should be considered to be experimental until the spec for these are
// finalized. Note, also, that Scheduler is expected to be defined as a global,
// but while the API is experimental we shouldn't expose it as such.
class Scheduler {
  constructor() {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }
 
  /**
   * @returns {Promise<void>}
   */
  yield() {
    if (!this[kScheduler])
      throw new ERR_INVALID_THIS('Scheduler');
    return setImmediate();
  }
 
  /**
   * @typedef {import('../internal/abort_controller').AbortSignal} AbortSignal
   * @param {number} delay
   * @param {{ signal?: AbortSignal }} [options]
   * @returns {Promise<void>}
   */
  wait(delay, options) {
    if (!this[kScheduler])
      throw new ERR_INVALID_THIS('Scheduler');
    return setTimeout(delay, undefined, { signal: options?.signal });
  }
}
 
module.exports = {
  setTimeout,
  setImmediate,
  setInterval,
  scheduler: ReflectConstruct(function() {
    this[kScheduler] = true;
  }, [], Scheduler),
};