【问题标题】:Am I handling errors the good way with async/await functions and Mongoose?我是用 async/await 函数和 Mongoose 处理错误的好方法吗?
【发布时间】: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


    【解决方案1】:

    简短回答 - 您的解决方案是正确的。你可以在控制器中有很多异步函数,调用它们并处理其中的错误。所有错误都将在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);
        }
    };
    

    【讨论】:

    • 感谢您的回答。我明白了,但是我发现看到大量“异步”前缀更有趣,更令人愉悦,如果按照您建议的方式执行,执行时间有什么不同吗?
    • 是的,有很大的不同,看看这个帖子:reddit.com/r/javascript/comments/5wnsbc/…
    • 我明白了,我会重写我的异步代码。非常感谢。
    • 如果找不到文件,它不会抛出 - result.ok 将为真,但 result.nModified 将为 0,就大多数应用程序而言,这在技术上仍然是一个错误案例,因为它没有对它试图找到的东西进行操作。
    • 你在说什么?如果找不到文档,findOne 返回 null。
    猜你喜欢
    • 2023-01-05
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2021-12-31
    • 2018-12-16
    • 2018-09-03
    • 2021-10-24
    • 2016-08-04
    相关资源
    最近更新 更多