Skip to content

Instantly share code, notes, and snippets.

@exodus4d
Created August 1, 2020 18:46
Show Gist options
  • Save exodus4d/6f02ed518c5a5494808366291ff1e206 to your computer and use it in GitHub Desktop.
Save exodus4d/6f02ed518c5a5494808366291ff1e206 to your computer and use it in GitHub Desktop.

Add more features [advanced]

At some point you might get limited by the Queue class as a data-structure. You have to add methods for new features, that break the definition of a Queue.

  • Multi threaded dequeue(): Maybe you want to break the limit of "one request after the other". E.g. run up to max 5 tasks parallel. You can replace this._pendingPromise (true|false) flag with a counter and check insinside dequeue().

    async dequeue() {
        if (this._pendingCount > 5) return false;
        ..
    }
    
  • Break out of the sequence: Image your queue is filled with "update" tasks for your UI module. When a user opens a full screen overlay, you might want to pause the queue for the time the overlay is up (the new overlay needs to be renders with highest priority)..

    You could inject a new task to the front of your queue for blocking. The task is a Promise that resolves a DeferredPromise which can not be resolved by the queue itself. It will be resolved by the script, on Overlay close

    • We need a way to insert new tasks at front (start) (1)
    • [Deferred Promise][13] implementation (2)
    this._blockPromise = false;    
    onOpen() {
        if (!this._blockPromise ) {
            this._blockPromise = new DeferredPromise(); // <-- (2)
            this._queue.enqueue(() => this._blockPromise .then(() => {
                this._blockPromise = null;
            }), 'start'); // <-- (1)
        }
    }
    
    onClose() {
        if (this._blockPromise) {
            this._blockPromise.resolve();
        }
    }
    
  • Nested Queues: Since our AutoQueue handles functions.. you can enqueue a task to queueA that is resolved when queueB is empty. So you can fill up a new queueB with tasks (you want to disable the default auto dequeue() when new tasks get enqueued) and add a "queueB resolver" task to queueA..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment