【发布时间】:2016-01-24 12:14:25
【问题描述】:
我刚开始使用 Promise 和 Bluebird。在调试时,我可以看到我的函数执行了两次:
首先我得到这个错误: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);
});
};
【问题讨论】:
-
如果你答应了,你的意思是写
findOneAsync? -
TypeError: Uncaught error: db.collection(...).findOneAsync is not a function -
你
Promise.promisifyAll(require("mongoose"))了吗? -
我应该把那行放在哪里?
-
var mongoose = Promise.promisifyAll(require("mongoose"))
标签: javascript node.js mongodb promise bluebird