【问题标题】:Effects of using await within a catch在 catch 中使用 await 的效果
【发布时间】:2017-04-22 09:13:12
【问题描述】:

我已经开始在最新版本的 node 中使用 async/await,但在尝试等待 catch 中的某些内容时遇到了问题。

假设我有以下功能来检查目录是否存在,如果不存在则根据需要创建文件夹:

const Promise = require("bluebird");
const fs = Promise.promisifyAll(require("fs"));
const path = require("path");

async function ensureDirectoryExists(directory) {
    try {
        console.log("Checking if " + directory + " already exists");
        await fs.openAsync(directory, "r");
    } catch (error) {
        console.log("An error occurred checking if " + directory + " already exists (so it probably doesn't).");
        let parent = path.dirname(directory);

        if (parent !== directory) {
            await ensureDirectoryExists(parent);
        }

        console.log("Creating " + directory);
        await fs.mkdirAsync(directory);
    }
}

如果我按以下方式调用它(为其提供不存在任何文件夹的目录路径),我会得到预期的输出(“确保目录存在。”最后出现)。

async function doSomething(fullPath) {
    await ensureDirectoryExists(fullPath);
    console.log("Ensured that the directory exists.");
}

但是,据我了解,每个异步函数都会返回一个 Promise,所以我认为以下方法也可以:

function doSomething2(fullPath) {
    ensureDirectoryExists(fullPath).then(console.log("Ensured that the directory exists."));
}

在这种情况下,即使产生了错误并且其余代码仍按预期执行,但在第一次调用 fs.openAsync 之后立即执行 then。 ensureDirectoryExists 是否不会返回承诺,因为它实际上并没有明确返回任何东西?是不是因为 catch 中的 await 而一切都搞砸了,而且它似乎只在从 doSomething 调用时才起作用?

【问题讨论】:

    标签: node.js asynchronous


    【解决方案1】:

    你打电话给.then你的承诺是错误的;它需要一个调用console.log函数

    ensureDirectoryExists(fullPath)
      .then(function() { // <-- note function here
        console.log("Ensured that the directory exists.");
      });
    

    或者简写,arrow functions:

    ensureDirectoryExists(fullPath)
      .then(() => console.log("Ensured that the directory exists."));
    

    如果你不将它包装在这样的函数中,console.log(...) 将被评估并立即运行(因此它可能会在ensureDirectoryExists 完成之前记录)。通过提供一个函数,promise 可以在异步函数完成时调用这个函数。

    【讨论】:

    • 是的,这就解释了 :)
    猜你喜欢
    • 2013-12-30
    • 2021-08-28
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2017-11-23
    相关资源
    最近更新 更多