When not to use Q.denodeify?

Q is a promising promise library, and Q.denodeify is a savior from pyramid of doom in NodeJS apps, but:

Do not use Q.denodeify for those NodeJS functions which don’t follow error-first callback approach.

Legit use:

var fs = require('fs'),
    q = require ('q'),
    // q.denodeify works on fs.readFile because it has error as first callback argument
    fs_readFile = q.denodeify( fs.readFile );

    .then(function( data ){
    }, function( err ){
        console.log('An error occurred: %s', err);

Illegit use:

var fs = require('fs'),
    q = require ('q'),
    // q.denodeify doesn't work properly on fs.exists because it doesn't have error as first callback argument
    fs_exists = q.denodeify( fs.exists );

    .then(function( exists ){
        // this part shall be invoked if file doesn't exist
        console.log('File exists: %s', exists);
    }, function( err ){
        // this part shall be invoked if file exists, not when there is an error
        console.log('An error occurred: %s', err);

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

One thought on “When not to use Q.denodeify?”

  1. For this exact reason I’ve written a standalone denodeify solution (https://github.com/matthew-andrews/denodeify) that works with *any* promise library & brings Promise-y goodness to those previously illegitimate use cases you described above:-

    So for your example of File Exists I would do this:-

    var denodeify = require(‘denodeify’);
    var fs = require(‘fs’);
    var exists = denodeify(fs.exists, function(exists) { return [undefined, exists]));

    .then(function(exists) {
    // exists will be true or false
    }, function() {
    // pretty hard to get hereā€¦

Leave a Reply

Your email address will not be published. Required fields are marked *