【发布时间】:2018-01-06 10:30:10
【问题描述】:
在我的网站上,我使用了很多异步函数来处理我网站的大部分内容,例如创建文章、管理员帐户、渲染视图等。
我养成了在控制器中创建尽可能多的异步函数的习惯,然后在异步执行块中执行所有这些函数,在这里我使用 try { } catch () { } 来捕获任何错误。但我想知道仅在该块上使用 try { } catch () { } 是否会让我错过一些错误?
另外,我使用 Mongoose 和原生 Promises。
而且,这是做这件事的好方法吗? 很长时间以来我一直在重复这种模式,所以我想知道是否必须更改一半的异步函数。
这是一个控制器示例:
// 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)
}
}())
},
提前致谢。
【问题讨论】:
标签: javascript node.js mongodb mongoose async-await