2017-04-22 18 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

是的,這將解釋它:) –