简体   繁体   English

mongoose static方法返回bluebird promise

[英]mongoose static method returns a bluebird promise

I am creating a mongoose static method 'load' so that my main controller function can use it (for chainning and error handling). 我正在创建一个mongoose静态方法'load',以便我的主控制器功能可以使用它(用于链接和错误处理)。

UserSchema.load('54ae92dd8b8eef540eb3a66d')
.then(....)
.catch(....);

The thing is the id is something wrong so I need to catch this error. 事情是id是错误的,所以我需要抓住这个错误。 and I am thinking it is better to do this in the model layer. 我认为最好在模型层中执行此操作。

When I do the following the controller can catch this error. 当我执行以下操作时,控制器可以捕获此错误。

UserSchema.statics.load = function(id) {

    if (!mongoose.Types.ObjectId.isValid(id)) {
        return Promise.resolve().then(function() {
            throw new Error('not a mongoose id');
        }); ------------( * )
    }

    return Promise.cast(this.findOne({
        _id: id
    }).exec());
};

But if I only do the following the error is not successfully thrown into the controller .catch function. 但是,如果我只执行以下操作,则错误未成功抛入控制器.catch函数。

AchievementSchema.statics.load = function(id) {
    if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('not a mongoose id');
    }
    return Promise.cast(this.findOne({
        _id: id
    }).exec());
};

so my question is am I doing this correctly? 所以我的问题是我正确地这样做了吗? If so is there easier ways to write the (*) statement? 如果有,是否有更简单的方法来编写(*)语句? What I am doing seems ugly.. Thanks. 我在做什么似乎很丑..谢谢。

Yes, there is a shorthand called Promise.reject . 是的,有一个名为Promise.reject的简写。

Your code in: 你的代码在:

if (!mongoose.Types.ObjectId.isValid(id)) {
    return Promise.resolve().then(function() {
        throw new Error('not a mongoose id');
    }); ------------( * )
}

Can be written as: 可以写成:

return Promise.reject(new Error("Not a mongoose id");

You can do even better though, Promise.method exists to ensure anything that might return a promise will return a promise: 你可以做得更好, Promise.method存在以确保任何可能返回promise的东西都会返回一个promise:

UserSchema.statics.load = Promise.method(function(id) {

    if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('not a mongoose id: ' + id);
    }
    return this.findOne({ _id: id }).exec());
});

This will both case the findOne result to a Bluebird trusted promise and convert the throw to a rejection for you. 这两种情况都会导致蓝鸟信任承诺的findOne结果,并将throw转换为拒绝。 You might want to consider throwing a subclass of Promise.OperationalError rather than Error though. 您可能想要考虑抛出Promise.OperationalError的子类而不是Error

As an unrelated tip Promise.cast was deprecated in favor of Promise.resolve over a year ago. 作为一个不相关的尖端Promise.cast是赞成不赞成的Promise.resolve在一年前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM