Bluebird promise is undefined?

2019-09-04 11:39发布

问题:

I'm using node 4.5+ and bluebird. I have the following code I intend to use with then:

var checkdir = function(directory) {
    return new Promise(function(resolve, reject) {
        fs.statAsync(directory).then(function() {
            resolve(true);
        }).catch(function(err) {
            if(err.code === 'ENOENT') {
                fs.mkdirAsync(directory).then(function() {
                    resolve(true);
                }).catch(function() {
                    reject(new Error('Can not create folder'));
                });
            } else {
                reject(new Error('Unknown fs stat error: ' + err));
            }
        });
    });
};

Async functions are from fs-extra-promise module. However, when I try to use this function, I get Unhandled rejection Error: Unknown error: TypeError: Cannot read property 'then' of undefined.

Calling:

                checkdir(dir).then(function() {
                    ...
                }).catch(function(err) {
                    reject(new Error('Unknown error: ' + err));
                });

What is wrong here?

回答1:

Using any kind of "exists" check in filesystem operations is actively discouraged in the node documentation. (Whether you do the exists check with stat or with exists is irrelevant.)

That means, in addition to Benjamin Gruenbaum's comment regarding the improper use of promises in general in your code, there is another important point to make:

The right way to create a directory is by calling mkdir unconditionally and ignoring EEXIST (compare this answer for more context).

var fs = Promise.promisifyAll(fs);

var ensureDir = function ensureDir(path) {
    return fs.mkdirAsync(path).catch((err) => { if (err.code !== 'EEXIST') throw err; });
}

You can use the mkdirp module to create a path recursively, like mkdir -p would.