以下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