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

标签 javascript node.js asynchronous promise

我在 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/

相关文章:

node.js - 推送到heroku的提交文件夹没有成功

javascript - CDN 上的服务器端渲染问题

python - 将 asyncio 与多处理结合起来会出现什么样的问题(如果有的话)?

javascript - jQuery 加载的 html 内容 - 检查图像是否已加载和呈现

JavaScript。引用文献问题。遗产。范围

javascript - 有没有办法在 require.js 中动态设置基本 url?

javascript - 如何从 Node.js 中的 URL 下载音频文件?

javascript - 如何重构异步重复代码

javascript - 使用 Node.js 从 MySQL 数据库进行 Ext js 树延迟加载

javascript - heroku Nodejs 应用程序在部署后崩溃