猫鼬承诺和Q承诺 [英] mongoose promise and Q promise
问题描述
[我会回答这个问题,但随时添加解决方案或其他可能发生的问题]
在使用q的诺言和猫鼬的nodejs项目上工作,我发现结合了两者的一些不直观的内容.
Working on a nodejs project where we use q promises heavily and mongoose I have found some unintuitive hickups combining the two.
第一个是猫鼬承诺没有.fail
或.catch
.
First one is that mongoose promise does not have .fail
or .catch
.
另一个是, Model.create 返回了一个承诺,该承诺调用了解决方法解析时使用多参数的函数.如果通过Q,则Q将仅使用第一个参数来调用resolve.
Another one is that Model.create returns a promise that calls the resolve function with mutliple arguments when resolved. If this goes through Q then Q will call the resolve with only the first argument.
请随时添加更多可能出现的问题;我将以解答方式解决这些问题.
Please feel free to add more problems that may occur; I will put how I solved these things in an answer.
推荐答案
You can simply use the Q
function to cast Mongoose promises to "proper" Q ones - this works in fact with every thenable.
所以只需使用
Q(someMongoosePromise) .then(…).catch(…);
多个参数是一个不同的问题.但是,有一个非常简单的技巧:将它们转换为数组并使用该数组.
Multiple arguments are a different problem. However, there is a very simple hack: convert them to an array and work with that.
Q(Model.create([doc1,doc2]).then(Array)) .spread(function(d1, d2){ … });
(此解决方案不适用于Model.create
返回单个数字的承诺的情况)
(This solution doesn't apply in case Model.create
returns a promise for a single number)
这篇关于猫鼬承诺和Q承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!