【问题标题】:nested promises node js嵌套承诺节点js
【发布时间】:2016-09-08 20:23:26
【问题描述】:

我阅读了来自here 的教程,但我不明白为什么第二个“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.close() 先于insertOne 解决
  • 不要嵌套承诺;这违背了使用它们的目的。

标签: javascript node.js mongodb promise


【解决方案1】:

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

【讨论】:

  • 第二次调用insertOne时没有返回承诺。
【解决方案2】:

见cmets

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

【讨论】:

  • 奇怪,它不起作用。第一条记录适用,但第二条和 db.close 不适用。
  • 你确定它应该是db1吗?而不是db?我认为这就是问题所在。我已经编辑了代码。
猜你喜欢
  • 2018-09-26
  • 2018-01-31
  • 2017-07-23
  • 2016-08-20
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多