Reputation: 1649
I just started working with promises and Bluebird. While debugging I can see that my function is executed twice:
First I get this error: TypeError: Uncaught error: Cannot read property 'then' of undefined
Then I see the function is executed again, and .then()
is executed successfully. Also I get the correct information printed in the console.
Why is this happening? The whole reason I'm implementing promises is because I want to wait with executing the then()
-action, because my data has to be retrieved first. But still the code jumps to the .then() action too early.
Why is this happening and how can I prevent it?
Here's my code:
exports.findUser = function(userId){
var ObjectID = require('mongodb').ObjectID;
var u_id = new ObjectID(userId);
db.collection('users')
.findOne({'_id': u_id})
.then(function(docs) { //executed twice, first time error, second time success
console.log(docs); //prints correct info once executed
return docs;
})
.catch(function(err) {
console.log(err);
});
};
Upvotes: 0
Views: 213
Reputation: 367
When working with the native npm module you should use callbacks here, like in the documentation. So for your example this would mean:
exports.findUser = function(userId){
var ObjectID = require('mongodb').ObjectID;
var u_id = new ObjectID(userId);
db.collection('users')
.findOne({'_id': u_id}, function(err, docs){
console.log(docs); //prints correct info once executed
return docs;
});
};
If you want to use promises than maybe you should consider using something like mongoose.
Upvotes: 1