UNPKG

prex

Version:

Async coordination primitives and extensions on top of ES6 Promises

82 lines (80 loc) 2.83 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 utils_1 = require("./utils"); /** * An asynchronous Stack. */ class AsyncStack { /** * Initializes a new instance of the AsyncStack class. * * @param iterable An optional iterable of values or promises. */ constructor(iterable) { this._available = undefined; this._pending = undefined; if (!utils_1.isIterable(iterable, /*optional*/ true)) throw new TypeError("Object not iterable: iterable."); if (!utils_1.isMissing(iterable)) { this._available = []; for (const value of iterable) { this._available.push(Promise.resolve(value)); } } } /** * Gets the number of entries in the stack. * When positive, indicates the number of entries available to get. * When negative, indicates the number of requests waiting to be fulfilled. */ get size() { if (this._available && this._available.length > 0) { return this._available.length; } if (this._pending && this._pending.length > 0) { return -this._pending.length; } return 0; } /** * Adds a value to the top of the stack. If the stack is empty but has a pending * pop request, the value will be popped and the request fulfilled. * * @param value A value or promise to add to the stack. */ push(value) { if (this._pending !== undefined) { const resolve = this._pending.shift(); if (resolve !== undefined) { resolve(value); return; } } if (this._available === undefined) { this._available = []; } this._available.push(Promise.resolve(value)); } /** * Removes and returns a Promise for the top value of the stack. If the stack is empty, * returns a Promise for the next value to be pushed on to the stack. */ pop() { if (this._available !== undefined) { const promise = this._available.pop(); if (promise !== undefined) { return promise; } } if (this._pending === undefined) { this._pending = []; } return new Promise(resolve => { this._pending.push(resolve); }); } } exports.AsyncStack = AsyncStack;