【问题标题】:.catch is causing error in bluebird-promised mongoose code.catch 导致蓝鸟承诺的猫鼬代码出错
【发布时间】:2016-05-25 19:57:24
【问题描述】:

我不知道为什么,但是在我的 bluebird 承诺代码中包含 .catch 会引发错误。我要么做错了,要么我错过了一些东西。

这是一个典型的 sn-p:

Event.find({classId : req.params.id, active : true})
    .then(function(events) {
        res.json({'events' : events})
    })

如果我把它改成

Event.find({classId : req.params.id, active : true})
    .then(function(events) {
        res.json({'events' : events})
    }).catch(function(err) {
        // do something
    })

然后我的测试,之前通过失败,500: server error

在我看来,这似乎是遵循 bluebird 文档以及我能够找到的任何代码示例。

我做错了吗? .find 中的错误在哪里??

如果重要的话,启用 bluebird Promise 的过程遵循一个熟悉的模式,并允许像冠军一样使用 .then 方法:

var mongoose = require('bluebird').promisifyAll(require('mongoose'));

这是我创建 mongoose 实例的地方,该实例用于为 Event 模型创建 Schema。


回复后:我已经开始使用.findAsync.findOneAsync,现在可以按预期捕获错误。

【问题讨论】:

  • 在promisification后你不应该使用findAsync
  • 如您所说的测试示例代码,它在我的测试中运行良好。可能是猫鼬版和蓝鸟版的问题?
  • @zangw : 你能给我你的版本让我验证吗?
  • @Yerken:你能帮我解决这个问题吗?我认为 .find 在 mongoose 中是异步的?
  • @DanielDonaldson,猫鼬版,4.4.3。蓝鸟版本 3.1.5

标签: node.js mongodb express mongoose bluebird


【解决方案1】:

正如 Yerken 所说,catch 是 Promise 的非标准功能,但几乎存在于所有 Promise 实现中,包括 bluebird

你可以设置 mongoose 使用bluebird promise 而不是它的默认值。

// Use bluebird
mongoose.Promise = require('bluebird');

您现在可以使用catch

【讨论】:

    【解决方案2】:

    catch 是 promise 的非标准特性,它存在于 Bluebird promisification 中,但至少在旧版本中不存在于实际的 mongoose find promise 中。

    在这种情况下,您想使用findAsync 而不是find

    【讨论】:

      猜你喜欢
      • 2015-10-27
      • 2015-11-19
      • 2016-06-04
      • 1970-01-01
      • 2016-11-21
      • 2016-09-23
      • 2019-01-17
      • 2016-06-10
      • 2015-03-05
      相关资源
      最近更新 更多