2017-04-22 45 views
1

我已经开始在最新版本的节点中尝试异步/等待,并且在尝试等待捕获内容时遇到问题。在捕获中使用await的效果

比方说,我有以下功能检查,看看是否存在一个目录,并创建文件夹,必要的,如果没有:

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."); 
} 

不过,据我所知,每个异步函数会返回一个承诺,所以我下面也将工作:

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

在这种情况下,虽然,当时是第一次之后执行调用fs.openAsync即使产生错误,并且其余代码仍按预期执行。 EnsureDirectoryExists是否不返回承诺,因为它实际上并未显式返回任何内容?一切都因为捕获内部的等待而搞砸了,它只是在从doSomething调用时才起作用?

回答

0

你打电话给.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可以在异步函数完成时调用这个函数。

+0

是的,这将解释它:) –