在异步代码promise中运行同步代码



我使用以下带有promise的代码,困扰我的是我使用readdirsyncfs.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");
});
}
}
});
});
});
}

我建议对所有逻辑流使用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
});

优点:

  1. 一致且完整的错误处理。您的版本中有多处错误没有得到正确处理
  2. 所有异步I/O,因此不会干扰服务器的扩展
  3. async/await使异步逻辑流更易于遵循

最新更新