Skip to content
Advertisement

How to implement a pseudo blocking async queue in JS/TS?

So here’s an oxymoron: I want to create an asynchronous blocking queue in javascript/typescript (if you can implement it without typescript, that’s fine). Basically I want to implement something like Java’s BlockingQueue expect instead of it actually being blocking, it would be async and I can await dequeues.

Here’s the interface I want to implement:

JavaScript

And I’d use it like so:

JavaScript

Any ideas?

Advertisement

Answer

It’s quite simple actually, dequeue will create a promise that enqueue will resolve. We just have to keep the resolvers in a queue – and also care about the case where values are enqueued before they are dequeued, keeping the already fulfilled promises in a queue.

JavaScript

I don’t know TypeScript, but presumably it’s simple to add the the necessary type annotations.

For better performance, use a Queue implementation with circular buffers instead of plain arrays, e.g. this one. You might also use only a single queue and remember whether you currently store promises or resolvers.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement