ix
Version:
The Interactive Extensions for JavaScript
88 lines (86 loc) • 3.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.timeout = exports.TimeoutAsyncIterable = exports.TimeoutError = void 0;
const tslib_1 = require("tslib");
const asynciterablex_js_1 = require("../asynciterablex.js");
const _sleep_js_1 = require("../_sleep.js");
const withabort_js_1 = require("./withabort.js");
const aborterror_js_1 = require("../../aborterror.js");
const isiterable_js_1 = require("../../util/isiterable.js");
const safeRace_js_1 = require("../../util/safeRace.js");
const returniterator_js_1 = require("../../util/returniterator.js");
/** @ignore */
class TimeoutError extends Error {
constructor(message = 'Timeout has occurred') {
super(message);
Object.setPrototypeOf(this, TimeoutError.prototype);
Error.captureStackTrace(this, this.constructor);
this.name = 'TimeoutError';
}
get [Symbol.toStringTag]() {
return 'TimeoutError';
}
}
exports.TimeoutError = TimeoutError;
Object.defineProperty(TimeoutError, Symbol.hasInstance, {
writable: true,
configurable: true,
value(x) {
return ((0, isiterable_js_1.isObject)(x) &&
(x.constructor.name === 'TimeoutError' || x[Symbol.toStringTag] === 'TimeoutError'));
},
});
const VALUE_TYPE = 'value';
const ERROR_TYPE = 'error';
/** @ignore */
class TimeoutAsyncIterable extends asynciterablex_js_1.AsyncIterableX {
constructor(source, dueTime) {
super();
this._source = source;
this._dueTime = dueTime;
}
[Symbol.asyncIterator](signal) {
return tslib_1.__asyncGenerator(this, arguments, function* _a() {
(0, aborterror_js_1.throwIfAborted)(signal);
const it = (0, withabort_js_1.wrapWithAbort)(this._source, signal)[Symbol.asyncIterator]();
try {
while (1) {
const { type, value } = yield tslib_1.__await((0, safeRace_js_1.safeRace)([
it.next().then((val) => {
return { type: VALUE_TYPE, value: val };
}),
(0, _sleep_js_1.sleep)(this._dueTime, signal).then(() => {
return { type: ERROR_TYPE };
}),
]));
if (type === ERROR_TYPE) {
throw new TimeoutError();
}
if (!value || value.done) {
break;
}
yield yield tslib_1.__await(value.value);
}
}
finally {
yield tslib_1.__await((0, returniterator_js_1.returnAsyncIterator)(it));
}
});
}
}
exports.TimeoutAsyncIterable = TimeoutAsyncIterable;
/**
* Applies a timeout policy for each element in the async-iterable sequence.
* If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is thrown.
*
* @template TSource The type of the elements in the source sequence.
* @param {number} dueTime Maximum duration in milliseconds between values before a timeout occurs.
* @returns {MonoTypeOperatorAsyncFunction<TSource>} The source sequence with a TimeoutError in case of a timeout.
*/
function timeout(dueTime) {
return function timeoutOperatorFunction(source) {
return new TimeoutAsyncIterable(source, dueTime);
};
}
exports.timeout = timeout;
//# sourceMappingURL=timeout.js.map