I am writing a utility in node.js that has to process and concatenate a large number of files every night. In synchronous pseudocode it would look like that (omitting try / catch for clarity):
while (true) {
var next = db.popNext();
if (!next) return;
out.append(next);
}
However, in the library I am using popNext()
is actually a node-style asynchronous method and rather looks like this: popNext(callback)
.
Since I am writing the middleware from scratch I could use --harmony
(e.g., generators), async or bluebird.
Ideally I would prefer something like:
forEachOrdered(db.popNext, (error, next, ok, fail) => {
if(error) return; // skip
// If there was an internal error, terminate the whole loop.
if(out.append(next)) ok();
else fail();
}).then(() => {
// All went fine.
}).catch(e => {
// Fail was called.
});
However, I am open to other 'standard' solutions. I was wondering what would be the most concise solution to this problem?
Edit Just spawning all (in a regular for loop) at the same time would probably not solve my problem since we're talking about 100k's and for every item I have to open and read a file, so I would probably run out of file descriptors.