Shorten promises

How to avoid unnecessary promise boilerplate code.

Asynchronous JavaScript code using promises can be very expressive, especially if you do not create unnecessary promises. For example, I would like to list all files in given folder with extension .md:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var Q = require('q');
var glob = require('glob');

function grabMarkdownFiles(folder) {
var defer = Q.defer();

glob(folder + '/*.md', function (err, files) {
if (err) {
defer.reject(err);
} else {
defer.resolve(files);
}
});
return defer.promise;
}

grabMarkdownFiles('../..').then(console.log, console.error);

The code works, but it has 5-6 lines of boilerplate code (creating and resolving deferred object) for 1 action line (globbing folder). Lets shorten this.

Q promises library I often use has a denodeify method to convert Nodejs callback functions into promise returning ones.

1
2
3
4
5
6
7
8
var Q = require('q');
var glob = Q.denodeify(require('glob'));

function grabMarkdownFiles(folder) {
return glob(folder + '/*.md');
}

grabMarkdownFiles('../..').then(console.log, console.error);

I would argue that grabMarkdownFiles function becomes unnecessary. Loading Q just to adapt glob also seems like overhead

1
2
var glob = require('q').denodeify(require('glob'));
glob('../../*.md').then(console.log, console.error);

So we went from 10 lines to 2. Not bad.