简体   繁体   English

嵌套的promises节点js

[英]nested promises node js

I read tutorial from here and I dont understand why second "insertOne" doesn`t work. 我从这里阅读教程,我不明白为什么第二个“insertOne”不起作用。 Thanks for help! 感谢帮助!

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

You have two asynchronous actions (db.insertOne) happening. 您发生了两个异步操作(db.insertOne)。

Therefore, you should have a .then after your second insertOne and close your connection 因此,你应该有一个.then你的第二个insertOne后并关闭连接

Code should look like this 代码应如下所示

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

See comments 看评论

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM