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」))'? –