Search code examples
javascriptpromisebluebird

Should I use promise for mkdir


I use the bluebird magic

var fs = Promise.promisifyAll(require('fs'));

and use

fs.readdirAsync(dest).then(function (val) {
        return val;
}).then(function (file) {

...

My question is for the following code (which is working) should I use the same and how I am talking about the mkdir function.

function createDir(folder) {
    return function (req, res, next) {
        if (typeof require.cache.per === 'undefined') {
            require.cache.per = {};
            require.cache.per.mk = false;
        }
        if (!require.cache.per.mk) {
            fs.mkdir(folder, function (e) {
                if (!!e && e.code !== 'EEXIST') {
                    console.log('Error to create  folder: ' + err);
                }
                require.cache.per.mk = true;
                next();
            });
        } else {
            next();
        }
    };
}

My Question is should I use promise here or not, what is recommended ? The code is working as expected...


Solution

  • A Promise simplifies, and unifies the interface. Either .promisify() or .promisifyAll() will do the trick.

    Then you can chain everything like this:

    fs.mkdir(dir)
        .then(function success(dir) {
            ...
        })
        .catch(function failure(err) {
            ...
        })
        .finally(function () {
        });
    

    However in node.js, the most important thing is to NOT block the I/O. It doesn't matter whether you use a Promise or a regular async/callback, as long as it's not blocking the main thread.

    It's ok to have synchronous code in script that you want to run in shell, but for regular applications you should never use blocking I/O operations on purpose.