2016-05-12 120 views
3

我從here閱讀教程,我不明白爲什麼第二個「insertOne」不起作用。感謝幫助!嵌套promises節點js

var Promise=require('promise'); 
var MongoClient=require('mongodb').MongoClient; 
var url = 'mongodb://localhost/EmployeeDB'; 
MongoClient.connect(url) 
    .then(function(db) 
{ 
    db.collection('Documents').insertOne({ 
     Employeeid: 1, 
     Employee_Name: "Petro"}) 
     .then(function(db1) { 
      db1.collection('Documents').insertOne({ 
       Employeeid: 2, 
       Employee_Name: "Petra"}) 
     }) 
     db.close(); 
    }); 
+5

'db.close()'在第一個'insertOne'解決之前調用 – MarkoCen

+2

不要嵌套promise;這就破壞了甚至使用它們的目的。 – ndugger

回答

3

發生了兩個異步操作(db.insertOne)。

因此,您應在第二insertOne後有.then和關閉連接

代碼應該是這樣的

{ 
    db.collection('Documents').insertOne({ 
     Employeeid: 1, 
     Employee_Name: "Petro"}) 
     .then(function(db1) { 
      db1.collection('Documents').insertOne({ 
       Employeeid: 2, 
       Employee_Name: "Petra"}) 
     }).then(function(db2) { 
       db.close(); 
     }) 
    }); 
+0

如果這適合你,請標記爲已解決! :) –

+3

它沒有將第二次調用的承諾返回給'insertOne'。 – robertklep

+0

對不起,此代碼無效。 –

0

看評論

MongoClient.connect(url) 
    .then(function(db) { 
     // you need a return statement here 
     return db.collection('Documents').insertOne({ 
      Employeeid: 1, 
      Employee_Name: "Petro" 
     }) 
      .then(function(record) { 
       // another return statement 
       // try db instead of db1 
       return db.collection('Documents').insertOne({ 
        Employeeid: 2, 
        Employee_Name: "Petra" 
       }) 
      }) 
     .then(function() { 
      // move the close here 
      db.close(); 
     }) 

}) 
// Add an error handler 
.then(null, function(error){ 
    console.log(error) 
}) 
+0

奇怪,它不起作用。第一條記錄是適用的,但第二條和db.close不適用。 –

+0

你確定它應該是'db1'嗎?而不是'db'?我認爲這是問題。我編輯了代碼。 –