Reputation: 1417
Faced an issue with Mongoose promises
MyModel.find().then((data)=> Promise.reject())
.catch(()=>console.log('first catch'))
.then(()=>console.log('ok'))
.catch(()=>console.log('second catch'));
after the execution I get
first catch
second catch
But if I do it with only native Promises:
Promise.reject()
.catch(()=>console.log('first catch'))
.then(()=>console.log('ok'))
.catch(()=>console.log('second catch'));
after the execution I get
first catch
ok
that is ok in terms of Promise docs
It seems that Mongoose uses own promise implementation
I have found that I can solve that by doing the following
new Promise((resolve, reject) => { MyModel.find().then((data) => reject()) })
.catch(()=>console.log('first catch'))
.then(()=>console.log('ok')
.catch(()=>console.log('second catch'));
It works as it should according the docs:
first catch
ok
Any suggestion how to work with that better?
Upvotes: 1
Views: 4327
Reputation: 538
you can also use of q library for promises. "q": "^1.4.1" q is the most populated library for java script promises.so we can use multiple promises result together.
var Q = require('q');
var promises= Q.all([
Model.find(),
Model2.find(),
Model3.find()
]);
promises.then(function(data) {
//console.log(data[0]);
//console.log(data[1]);
//console.log(data[2]);
});
promises.then(null, function(err) {
});
Upvotes: 0
Reputation: 19607
Mongoose uses Promises/A+ conformant promises. For backwards compatibility, Mongoose 4 returns mpromise
promises by default.
If you want to use advanced promise features, you should use library like bluebird or native ES6 promises. To do that just set mongoose.Promise
to your favorite ES6-style promise constructor and mongoose will use it:
require('mongoose').Promise = Promise;
// or
require('mongoose').Promise = require('bluebird');
Upvotes: 1