# 承诺（promises）

> 原文：[Built-in Promises](http://mongoosejs.com/docs/promises.html)\
> 翻译：小虾米（QQ:509129）

## 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承诺。

```javascript
  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()`功能。

```javascript
    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)上。

```javascript
  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。

```javascript
    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'));
    });
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mongoose.shujuwajue.com/guide/promises.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
