UNPKG

prex

Version:

Async coordination primitives and extensions on top of ES6 Promises

86 lines (84 loc) 2.9 kB
"use strict"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0. See LICENSE file in the project root for details. ***************************************************************************** */ Object.defineProperty(exports, "__esModule", { value: true }); const list_1 = require("./list"); const cancellation_1 = require("./cancellation"); const utils_1 = require("./utils"); const adapter_1 = require("./adapter"); /** * Asynchronously notifies one or more waiting Promises that an event has occurred. */ class ManualResetEvent { /** * Initializes a new instance of the ManualResetEvent class. * * @param initialState A value indicating whether to set the initial state to signaled. */ constructor(initialState) { this._waiters = new list_1.LinkedList(); if (utils_1.isMissing(initialState)) initialState = false; if (!utils_1.isBoolean(initialState)) throw new TypeError("Boolean expected: initialState."); this._signaled = !!initialState; } /** * Gets a value indicating whether the event is signaled. */ get isSet() { return this._signaled; } /** * Sets the state of the event to signaled, resolving one or more waiting Promises. */ set() { if (!this._signaled) { this._signaled = true; for (const waiter of this._waiters.drain()) { if (waiter) waiter(); } } } /** * Sets the state of the event to nonsignaled, causing asynchronous operations to pause. */ reset() { this._signaled = false; } /** * Asynchronously waits for the event to become signaled. * * @param token A CancellationToken used to cancel the request. */ wait(token) { return new Promise((resolve, reject) => { const _token = adapter_1.getToken(token); _token.throwIfCancellationRequested(); if (this._signaled) { resolve(); return; } const node = this._waiters.push(() => { registration.unregister(); if (_token.cancellationRequested) { reject(new cancellation_1.CancelError()); } else { resolve(); } }); const registration = _token.register(() => { if (node.list) { node.list.deleteNode(node); reject(new cancellation_1.CancelError()); } }); }); } } exports.ManualResetEvent = ManualResetEvent;