以下this snippet我想写一个循环槽目录,查找目录,并从这些目录中读取XML文件名的函数(我知道文件夹结构将始终保持相同)。到目前为止,我的函数按预期工作,但是当我试图从函数返回时,我只是得到Promise对象。蓝鸟 - 功能返回承诺对象,而不是实际数据
我的代码:
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const path = require('path');
function getFileNames(rootPath) {
// Read content of path
return fs.readdirAsync(rootPath)
// For every file in path
.then(function(directories) {
// Filter out the directories
return directories.filter(function(file) {
return fs.statSync(path.join(rootPath, file)).isDirectory();
});
})
// For every directory
.then(function(directories) {
return directories.map(function(directory) {
// Read file in the directory
return fs.readdirAsync(path.join(rootPath, directory))
.filter(function(file) {
return path.extname(file) == '.XML';
})
.then(function(files) {
// Do something with the files
return files;
});
});
});
}
getFileNames('./XML').then(function(files) {
console.log(files);
});
当我console.log(files)
内getFileNames
最后.then
函数中,我得到的文件名的实际阵列控制台。但是,当我运行上面的代码我得到这样的输出:
[ Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined },
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined },
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined },
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined },
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined } ]
为什么会出现这种情况,如何解决?
stil得到相同的输出 –
@MihaŠušteršič我编辑answer – stasovlas