Can someone give me an example on how to use a Promise with mongoose. Here is what I have, but its not working as expected:
app.use(function (req, res, next) { res.local('myStuff', myLib.process(req.path, something)); console.log(res.local('myStuff')); next(); });
and then in myLib, I would have something like this:
exports.process = function ( r, callback ) { var promise = new mongoose.Promise; if(callback) promise.addBack(callback); Content.find( {route : r }, function (err, docs) { promise.resolve.bind(promise)(err, docs); }); return promise; };
At some point I am expecting my data to be present, but how can I access it, or get at it?
If you're an advanced user, you may want to plug in your own promise library like bluebird. Just set mongoose. Promise to your favorite ES6-style promise constructor and mongoose will use it.
While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.
A Promise is an object returned by the asynchronous method call that allows you to access information on the eventual success or failure of the operation that they wrap.
In the current version of Mongoose, the exec()
method returns a Promise, so you can do the following:
exports.process = function(r) { return Content.find({route: r}).exec(); }
Then, when you would like to get the data, you should make it async:
app.use(function(req, res, next) { res.local('myStuff', myLib.process(req.path)); res.local('myStuff') .then(function(doc) { // <- this is the Promise interface. console.log(doc); next(); }, function(err) { // handle error here. }); });
For more information about promises, there's a wonderful article that I recently read: http://spion.github.io/posts/why-i-am-switching-to-promises.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With