Bluebird promise is undefined?

让人想犯罪 __ 提交于 2019-12-25 08:29:50

问题


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.



来源:https://stackoverflow.com/questions/39446644/bluebird-promise-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!