UNPKG

prex

Version:

Async coordination primitives and extensions on top of ES6 Promises

57 lines (55 loc) 1.75 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 adapter_1 = require("./adapter"); /** * Asynchronously notifies one or more waiting Promises that an event has occurred. */ class Pulsar { constructor() { this._waiters = new list_1.LinkedList(); } /** * Notifies the next waiter. */ pulse() { const waiter = this._waiters.shift(); if (waiter) waiter(); } /** * Notifies all waiters. */ pulseAll() { for (const waiter of this._waiters.drain()) { if (waiter) waiter(); } } /** * Asynchronously waits for the the next pulse. * * @param token A CancellationToken used to cancel the request. */ wait(token) { return new Promise((resolve, reject) => { const _token = adapter_1.getToken(token); _token.throwIfCancellationRequested(); const node = this._waiters.push(() => { registration.unregister(); resolve(); }); const registration = _token.register(() => { node.list.deleteNode(node); reject(new cancellation_1.CancelError()); }); }); } } exports.Pulsar = Pulsar;