UNPKG

prex

Version:

Async coordination primitives and extensions on top of ES6 Promises

78 lines (76 loc) 2.71 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 AutoResetEvent { /** * Initializes a new instance of the AutoResetEvent 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; } /** * Sets the state of the event to signaled, resolving one or more waiting Promises. * The event is then automatically reset. */ set() { if (!this._signaled) { this._signaled = true; if (this._waiters.size > 0) { for (const waiter of this._waiters.drain()) { if (waiter) waiter(); } this._signaled = false; } } } /** * 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(); this._signaled = false; return; } const node = this._waiters.push(() => { registration.unregister(); resolve(); }); const registration = _token.register(() => { node.list.deleteNode(node); reject(new cancellation_1.CancelError()); }); }); } } exports.AutoResetEvent = AutoResetEvent;