2016-01-21 111 views
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); 
     }); 
}; 
+0

如果你对它进行了promisified,你的意思是写'findOneAsync'? –

+0

'TypeError:Uncaught error:db.collection(...)。findOneAsync is not a function' – Forza

+0

'Promise.promisifyAll(require(“mongoose”))'? –

回答

1

当你要在这里documentation使用回调,像本地NPM模块工作。因此,对于你的例子,这将意味着:

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; 
     }); 
}; 

如果你想使用的承诺比也许你应该考虑使用类似mongoose

相关问题