gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:20:50 24 4
gpt4 key购买 nike

我在 promise 中使用了以下代码,令我困扰的是我使用了 readdirsyncfs.statSync inside promise, 可能是错误的,我问它,因为目前它按预期工作,但我想知道如果我能进入问题。或者有更好的方法来编写它?

我所做的是提取根文件夹,然后提取 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 使异步逻辑流程更易于遵循

关于javascript - 在异步代码中运行同步代码 - promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com