使用Bluebird进行猫鼬承诺的正确方法是什么? [英] What is the correct way of using Bluebird for Mongoose promises?

查看:75
本文介绍了使用Bluebird进行猫鼬承诺的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读文档和文章,似乎每个人都描述了一起使用Mongoose和Bluebird的另一种方式.甚至正式的Mongoose文档也说了些什么,而Bluebird文档说

I've been reading documentaion and articles and everyone seems to describe a different way about using Mongoose and Bluebird together. Even the official Mongoose documentation says something and Bluebird documentaion says another thing.

根据猫鼬:

mongoose.Promise = require('bluebird');

根据蓝鸟:

var Promise = require("bluebird");
Promise.promisifyAll(require("mongoose"));

据我所知,如果您选择猫鼬方式,则示例查询将类似于:

So to my understanding, if you pick the Mongoose way a sample query would be like:

User.findById('someId')
    .then(function(){
        // do stuff
    })
    .catch(function(err){
        // handle error
    })

但是在Mongoose文档中它也说:

But also in Mongoose docs it says that:

猫鼬查询不是承诺.但是,它们确实具有.then()函数用于yield和async/await.如果您需要完整的承诺,请使用.exec()函数.

Mongoose queries are not promises. However, they do have a .then() function for yield and async/await. If you need a fully-fledged promise, use the .exec() function.

因此,在这种情况下, .then 是否在承诺之上?

So in this case, is .then above a promise or not?

如果您使用Bluebird方式:

If you go with Bluebird way:

User.findById('someId')
    .execAsync()
    .then(function(){
        // do stuff
    })
    .catch(function(err){
        // handle error
    })

或者甚至跳过 execAsync()并从 findByIdAsync 开始.

Or maybe even skip execAsync() and start with findByIdAsync instead.

确实与其他文献相混淆.如果有人能对此有所启发,我将不胜感激.

Really confused with different documentaion. I'd appreciate if someone can shed some light into this.

推荐答案

来自Bluebird文档

Promise.promisifyAll(
    Object target,
    [Object {
        suffix: String="Async",
        multiArgs: boolean=false,
        filter: boolean function(String name, function func, Object target, boolean passesDefaultFilter),
        promisifier: function(function originalFunction, function defaultPromisifier)
    } options] ) -> Object

如您所见,默认情况下,promisifyAll会添加后缀'Asyns',因此,如果您使用的是这种promisification方式:

as you can see, by default, promisifyAll add suffix 'Asyns', so if you are using this way of promisification:

var Promise = require("bluebird");
Promise.promisifyAll(require("mongoose"));

User.findById 的异步版本将为 User.findByIdAsync

猫鼬.诺言

然后使用

mongoose.Promise = require('bluebird');

内置的Promise机制替换为库: query.exec().constructor 替换为 require('bluebird'),所以改为 .exec()以获得退货承诺,您可以将bluebird概率直接用于

built-in promise mechanism replaced by library: query.exec().constructor replaced by require('bluebird') so instead .exec() for return promise, you can use bluebird probabilities directly for mongoose queries like

User.findOne({}).then(function(user){
    // ..
})  

这篇关于使用Bluebird进行猫鼬承诺的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆