我使用带有承诺的以下代码,令我困扰的是我使用readdirsync
和
fs.statSync
内在承诺中,可能是错的,我要问一下,因为当前它按预期运行,但我想知道
如果我遇到了问题。或者有更好的书写方式?
我所做的是提取根文件夹,然后提取Childs
function unzip(filePath, rootP, fileN) {
return new Promise((resolve, reject) => {
extract(filePath, {dir: rootP, defaultDirMode: '0777'}, (err) => {
if (err) {
reject(err);
}
fs.readdirSync(path.join(rootP, fileN
)).forEach((file) => {
const zipPath = path.join(rootP, fileN
, file);
if (fs.statSync(zipPath).isFile()) {
if (path.extname(file) === '.zip') {
let name = path.parse(file).name;
let rPath = path.join(rootP, fileN)
return unzipChilds(zipPath, rPath, name)
.then(() => {
return resolve(“Done");
});
}
}
});
});
});
}
答案 0 :(得分:1)
我建议对所有逻辑流使用Promises和async/await
:
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const extractAsync = Promise.promisify(extract);
async function unzip(filePath, rootP, fileN) {
await extractAsync(filePath, {dir: rootP, defaultDirMode: '0777'});
let files = await fs.readdirAsync(path.join(rootP, fileN));
for (let file of files) {
const zipPath = path.join(rootP, fileN, file);
let stats = await fs.statAsync(zipPath);
if (stats.isFile() && path.extname(file) === '.zip') {
let name = path.parse(file).name;
let rPath = path.join(rootP, fileN);
await unzipChilds(zipPath, rPath, name);
}
}
}
// usage:
unzip(...).then(() => {
// all done here
}).catch(err => {
// process error here
});
优势:
async/await
使异步逻辑流程更易于遵循