下面有一些代码将返回目录中具有某些键和值的所有文件。我想要的键之一是带有 bool 值的 isDirectory。
下面的代码工作得很好,但我想知道是否有一种方法可以删除 Promise.all/iteating 的 promise ,并将 stat.isDirectory()
的解析值直接推送到我的 map 中的文件对象。
我尝试过但失败的解决方案:
我尝试过这样的事情:
isDirectory: fs.statAsync(path).then((stat) => stat.isDirectory())
然后对所有 isDirectory
键执行 Promise.all
工作代码:
const Promise = require('bluebird'),
os = require('os'),
_ = require('lodash'),
fs = Promise.promisifyAll(require('fs')),
desktopPath = `${os.homedir()}/Desktop`;
let files = [];
return fs.readdirAsync(desktopPath)
.then((filesName) => files = _.map(filesName, (fileName) => ({
path: `${desktopPath}/${fileName}`,
name: fileName,
ext: _.last(fileName.split('.'))
})))
.then(() => Promise.all(_.map(files, (file) => fs.statAsync(file.path))))
.then((stats) => _.forEach(stats, (stat, idx) => {
files[idx].isDirectory = stat.isDirectory();
}))
.then(() => {
console.log(files);
})
有没有办法删除最后的 Promise.all 和 _.forEach 部分?而是在我的 map 中执行这些操作?
最佳答案
您无法完全删除 Promise.all
,因为您需要等待所有文件完成后再使用最终结果。但您可以通过一次 .then()
调用完成这一切。
由于 map
是同步的,因此它不会等待 fs.statAsync
完成。但是您可以创建一个 fs.statAsync
的 Promise 数组,这些 Promise 会解析最终的文件对象,然后只需使用 Promise.all
等待所有这些都完成即可。
带有一些澄清注释的详细版本:
fs.readdirAsync(desktopPath)
.then(fileNames => {
// Array of promises for fs.statAsync
const statPromises = fileNames.map(fileName => {
const path = `${desktopPath}/${fileName}`;
// Return the final file objects in the promise
return fs.statAsync(path).then(stat => ({
path,
name: fileName,
ext: _.last(fileName.split(".")),
isDirectory: stat.isDirectory()
}));
});
// Promise.all to wait for all files to finish
return Promise.all(statPromises);
})
.then(finalFiles => console.log(finalFiles));
以及紧凑版本:
fs.readdirAsync(desktopPath)
.then(fileNames => Promise.all(
fileNames.map(fileName =>
fs.statAsync(`${desktopPath}/${fileName}`).then(stat => ({
path: `${desktopPath}/${fileName}`,
name: fileName,
ext: _.last(fileName.split(".")),
isDirectory: stat.isDirectory()
})))
))
.then(finalFiles => console.log(finalFiles));
关于javascript - Node Promise 返回具有已解决 Promise 值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42489268/