Simple async queue and code enmity

I’m recently coding some node.js for fun and at some point I happened to need a simple command queue to process some requests without interrupting each other. Nothing extraordinary. Probably there’s tons of libraries that help you achieve that, especially in such a jungle that npm is.

I thought, dead simple, let’s code. Coding well-defined, isolated problems can actually be quite enjoyable, right? Actually a lot more enjoyable than trying to find the right library, checking if it behaves as promised, and how it achieves it’s purpose. Maybe it does some magic, maybe some quantum processing, maybe some redundant computation as it was once brought to widespread attention with infamous leftpad.

Anyway, I started coding, probably like lot of other people would… “let’s have an array called queue, we will push tasks to it & shift them…”. But here’s what I ended up with:

class SimpleCommandQueue {
  constructor(nextProcessor) {
this.nextProcessor = nextProcessor
this.lastPromise = Promise.resolve({})
}
  process(command) {
let executedPromise = new Promise((resolve, reject) => {
let processAndResolve = () => {
this.nextProcessor.process(command).then(
result => resolve(result),
error => reject(error)
)
}
this.lastPromise.then(
processAndResolve,
processAndResolve
)
})
    this.lastPromise = executedPromise
return executedPromise
}
}

(you can find the code here)

It basically just stacks promises on top of each other, starting from one, that is initially resolved.

I liked it. Simple, short & elegant. No if/else, no loops. Works on top of a built-in feature (ES6). You may have heard that code is your enemy. I totally agree. The less code, the weaker the enemy. And you probably all know and I don’t mean Perl golf contests here.

I’d actually say that code is a minefield. The less code, the less place for bugs to come up, the less maintenance required, the less to explain to your colleagues. Our sanity and well-being as programmers depends on (among others) having less code to deal with and on the code being simple enough.

Less code is good for all of us. But my question is: did I achieve this goal when I wrote my own chunk of code to solve a well-known problem. It was short and simple indeed, but I could pull a library from npm and have even less code to deal with. Would I?

I think we all agree that less code is better. But which way to go: try to write stuff yourself and keep it as simple as possible, or try to find a library for everything? I know it’s probably a balancing act, but it would be interesting to hear what your thoughts are.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.