Node.js 在捕获中使用等待的效果
我已经开始在最新版本的node中使用async/await,在尝试等待捕获中的某个内容时遇到了问题 假设我有以下功能来检查目录是否存在,如果不存在,则根据需要创建文件夹:Node.js 在捕获中使用等待的效果,node.js,asynchronous,Node.js,Asynchronous,我已经开始在最新版本的node中使用async/await,在尝试等待捕获中的某个内容时遇到了问题 假设我有以下功能来检查目录是否存在,如果不存在,则根据需要创建文件夹: const Promise = require("bluebird"); const fs = Promise.promisifyAll(require("fs")); const path = require("path"); async function ensureDirectoryExists(directory)
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);
}
}
如果我以以下方式调用它(提供一个不存在任何文件夹的目录路径),我将得到预期的输出(“确保目录存在。”排在最后)
但是,据我所知,每个异步函数都会返回一个承诺,因此我认为以下方法也可以:
function doSomething2(fullPath) {
ensureDirectoryExists(fullPath).then(console.log("Ensured that the directory exists."));
}
但在本例中,then将在第一次调用fs.openAsync后立即执行,即使出现错误,其余代码仍按预期执行。EnsureRedirectoryExists是否因为没有显式返回任何内容而不返回承诺?是不是所有的事情都因为等待而变得一团糟,而只有当你从某个地方被召唤时,它才显得有效?你对你的承诺的召唤是错误的;它需要一个调用console.log的函数:
确保重定向存在(完整路径)
.then(function(){//console.log(“确保目录存在”);
如果您不将其封装在这样的函数中,console.log(…)
将被计算并立即运行(因此它可能会在ensureRedirectoryExists
完成之前进行日志记录)。通过改为提供函数,promise可以在异步函数完成时调用此函数。您对promise的调用是错误的;它希望函数调用控制台。log:
确保重定向存在(完整路径)
.then(function(){//console.log(“确保目录存在”);
如果您不将其封装在这样的函数中,
console.log(…)
将被计算并立即运行(因此它可能会在ensureRedirectoryExists
完成之前进行日志记录)。通过提供函数,promise可以在异步函数完成时调用此函数。Yep,这可以解释:)Yep,这可以解释:)
function doSomething2(fullPath) {
ensureDirectoryExists(fullPath).then(console.log("Ensured that the directory exists."));
}