ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 承诺(promises) > 原文:[Built-in Promises](http://mongoosejs.com/docs/promises.html) ## Built-in Promises Mongoose异步操作,像`.save()`和查询,返回[Promises/A+ conformant promises](https://promisesaplus.com/)。这意味着你可以像`MyModel.findOne({}).then()`和 `MyModel.findOne({}).exec()`(如果你使用[co](https://www.npmjs.com/package/co)包)。 为了向后兼容,Mongoose 4返回默认mpromise承诺。 ``` var gnr = new Band({ name: "Guns N' Roses", members: ['Axl', 'Slash'] }); var promise = gnr.save(); assert.ok(promise instanceof require('mpromise')); promise.then(function (doc) { assert.equal(doc.name, "Guns N' Roses"); }); ``` ### Queries are not promises Mongoose查询不是承诺。然而,他们也有一个`.then()`功能为产量和异步/等待。如果你需要一个完全成熟的承诺,用`.exec()`功能。 ``` var query = Band.findOne({name: "Guns N' Roses"}); assert.ok(!(query instanceof require('mpromise'))); // A query is not a fully-fledged promise, but it does have a `.then()`. query.then(function (doc) { // use doc }); // `.exec()` gives you a fully-fledged promise var promise = query.exec(); assert.ok(promise instanceof require('mpromise')); promise.then(function (doc) { // use doc }); ``` ### Plugging in your own Promises Library > Mongoose 4.1.0 新特性 而mpromise满足基本使用的情况下,高级用户可能想插上自己喜欢的[ES6风格](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)[承诺类库](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)像[bluebird](https://www.npmjs.com/package/bluebird),或只使用本地的ES6承诺。只需要设置`mongoose.Promise`到你喜欢的ES6风格承诺构造函数,mongoose会使用它。 随着本土承诺ES6Mongoose试验,[bluebird](https://www.npmjs.com/package/bluebird)和[q](https://www.npmjs.com/package/q)。任何承诺类库,理论上导出一个ES6风格的构造函数应该工作,但理论往往不同于实践。如果你发现一个bug,开放式问题在[GitHub](https://github.com/Automattic/mongoose/issues)上。 ``` var query = Band.findOne({name: "Guns N' Roses"}); // Use native promises mongoose.Promise = global.Promise; assert.equal(query.exec().constructor, global.Promise); // Use bluebird mongoose.Promise = require('bluebird'); assert.equal(query.exec().constructor, require('bluebird')); // Use q. Note that you **must** use `require('q').Promise`. mongoose.Promise = require('q').Promise; assert.ok(query.exec() instanceof require('q').makePromise); ``` ### Promises for the MongoDB Driver mongoose。承诺的属性集的mongoose用承诺。然而,这并不影响底层的MongoDB的驱动程序;。如果你使用了底层的驱动程序,例如`Model.collection.db.insert()`,你需要做一些额外的工作来改变其所承诺的类库。注意,下面的代码假定mongoose> = 4.4.4。 ``` var uri = 'mongodb://localhost:27017/mongoose_test'; // Use bluebird var options = { promiseLibrary: require('bluebird') }; var db = mongoose.createConnection(uri, options); Band = db.model('band-promises', { name: String }); db.on('open', function() { assert.equal(Band.collection.findOne().constructor, require('bluebird')); }); ```