嵌套的promise节点js

nested promises node js

本文关键字:js 节点 promise 嵌套      更新时间:2023-09-26

我从这里读了教程,我不明白为什么第二个"insertOne"不起作用。谢谢你的帮助!

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

您有两个异步操作(db.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();
        })
    });

参见评论

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