我不知道为什么,但在我的蓝鸟宣传的代码中包含.catch
会引发错误。我做错了,或者我错过了什么。
这是一个典型的代码段:
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
。
在我看来,我可以按照蓝鸟文档和我能找到的任何代码示例进行操作。
我做错了吗?以及.find
中的错误在哪里?
如果重要的话,启用蓝鸟承诺的过程遵循熟悉的模式,并允许像冠军一样使用.then
方法:
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
这是我创建用于为事件模型创建Schema的mongoose实例的地方。
回答:我已开始使用.findAsync
和.findOneAsync
,我现在可以按预期捕获错误。
答案 0 :(得分:2)
正如Yerken所说,catch
是承诺的非标准功能,但几乎所有承诺都包含在bluebird
中。
您可以将mongoose设置为使用bluebird
承诺而不是默认承诺。
// Use bluebird
mongoose.Promise = require('bluebird');
您现在可以使用catch
。
答案 1 :(得分:0)
catch
是承诺的非标准功能,它存在于Bluebird
promisification中,但不存在于实际的mongoose find
承诺中,至少在旧版本中是这样。
在这种情况下,您希望使用findAsync
代替find