0
我刚开始使用promise和Bluebird。虽然调试我可以看到我的功能被执行两次:Bluebird .then():不工作,因为它应该
首先,我得到这个错误:TypeError: Uncaught error: Cannot read property 'then' of undefined
然后我看到了功能再次被执行,.then()
被成功执行。我也可以在控制台上打印正确的信息。
这究竟是为什么?我实现承诺的全部原因是因为我想等待执行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);
});
};
如果你对它进行了promisified,你的意思是写'findOneAsync'? –
'TypeError:Uncaught error:db.collection(...)。findOneAsync is not a function' – Forza
'Promise.promisifyAll(require(“mongoose”))'? –