2016-01-21 125 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