2017-07-31 40 views
1

在我的網站上,我使用了很多異步功能來處理我網站的大部分內容,例如創建文章,管理員帳戶,渲染視圖等。我是用異步/等待函數和Mongoose處理錯誤的好方法嗎?

我養成了創建儘可能多的異步功能的習慣我需要在控制器內部,然後在異步執行塊內執行所有這些操作,我使用try {} catch(){}來捕獲任何錯誤。但是,我想知道是否僅在該塊上使用try {} catch(){}會讓我錯過一些錯誤?

此外,我用Mongoose與本地承諾。

而且,這是做到這一點的好方法嗎? 我重複這種模式,因爲很多時間,所以我想知道如果我不得不改變一半的異步功能。

這裏是一個控制器例如:

// getArticle {{{ 
    /** 
    * Handles the view of an article 
    * 
    * @param {HTTP} request 
    * @param {HTTP} response 
    */ 
    getArticle: function (request, response) { 
    /** 
    * Get the article matching the given URL 
    * 
    * @async 
    * @returns {Promise} Promise containing the article 
    */ 
    async function getArticle() { 
     let url = request.params.url 

     return Article 
     .findOne({ url: url }) 
     .populate('category', 'title') 
     .exec() 
    } 

    /** 
    * Asynchronous execution block 
    * 
    * @async 
    * @throws Will throw an error to the console if it catches one 
    */ 
    (async function() { 
     try { 
     let article = await getArticle() 

     response.render('blog/article', { 
      title: article.title, 
      article: article 
     }) 
     } catch (error) { 
     console.log(error) 
     } 
    }()) 
}, 

預先感謝。

回答

2

簡答 - 您的解決方案是正確的。你可能在控制器中有很多異步函數,調用它們並處理錯誤。所有錯誤將在catch塊中處理。

但是,您不需要將async添加到所有這些功能。如果您不想在該函數中使用異步調用的結果,只需返回承諾。你也可以不用將控制器的主代碼封裝在函數中,你可以將控制器的動作標記爲異步函數,並在其中添加代碼。

getArticle: async function(request, response) { 
    function getArticle() { 
     let url = request.params.url 

     return Article 
     .findOne({ url: url }) 
     .populate('category', 'title') 
     .exec() 
    } 

    try { 
     let article = await getArticle(); 

     response.render('blog/article', { 
     title: article.title, 
     article: article 
     }) 
    } catch (error) { 
     console.log(error); 
    } 
}; 
+0

謝謝你的回答。我明白了,但是我發現它更有趣,更令人高興的是,我看到大量的「異步」前綴,如果按照您的建議我這樣做,執行時間是否有區別? –

+0

是的,有一個很大的區別,看看這篇文章:https://www.reddit.com/r/javascript/comments/5wnsbc/async_functions_performance_question/ – alexmac

+0

我看到了,我會重寫我的異步代碼。非常感謝。 –