【发布时间】: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