我刚刚开始使用promises和Bluebird。在调试时,我可以看到我的函数被执行了两次:
首先我得到这个错误:TypeError: Uncaught error: Cannot read property 'then' of undefined
然后,我看到函数被再次执行,并且.then()被成功执行。另外,我还可以在控制台中打印出正确的信息。
为什么会发生这种情况?我实现promises的全部原因是因为我想等待执行then()-action,因为必须首先检索我的数据。但是代码仍然过早地跳到了.then()操作。
为什么会发生这种情况,我如何防止它发生?
下面是我的代码:
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);
});
};发布于 2016-01-21 23:39:14
当使用原生npm模块时,您应该在这里使用回调,就像在documentation中一样。因此,对于您的示例,这意味着:
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;
});
};如果你想使用promises,那么也许你应该考虑使用像mongoose这样的东西。
https://stackoverflow.com/questions/34926796
复制相似问题