我是用async / await函数和Mongoose处理错误的好方法吗?

在我的网站上,我使用了很多asynchronousfunction来处理我网站的大部分内容,例如创build文章,pipe理员帐户,渲染视图等。

我习惯于在控制器中创build需要的asynchronous函数,然后在asynchronous执行块内部执行所有这些函数,在那里使用try {} catch(){}来捕获任何错误。 但是,我想知道是否只使用try {} catch(){}使得我错过了一些错误?

另外,我用Mongoose和Native Promises。

而且,这是做到这一点的好方法吗? 我重复这种模式,因为很多时间,所以我想知道如果我必须改变一半的asynchronousfunction。

这是一个控制器的例子:

// 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) } }()) }, 

提前致谢。

简短的回答 – 您的解决scheme是正确的 你可以在控制器中有很多asynchronous函数,调用它们并处理错误。 所有错误将在catch块中处理。

但是,您不需要为所有这些function添加async 。 如果你不想在该函数中使用asynchronous调用的结果,只要返回promise。

你也不需要把控制器的主代码封装在函数中,你可以把控制器的动作标记为asynchronous函数并在其中添加代码。

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