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)
}
}())
},
預先感謝。
謝謝你的回答。我明白了,但是我發現它更有趣,更令人高興的是,我看到大量的「異步」前綴,如果按照您的建議我這樣做,執行時間是否有區別? –
是的,有一個很大的區別,看看這篇文章:https://www.reddit.com/r/javascript/comments/5wnsbc/async_functions_performance_question/ – alexmac
我看到了,我會重寫我的異步代碼。非常感謝。 –