【问题标题】:Sync Promises for initialize MongoDB database同步 Promise 以初始化 MongoDB 数据库
【发布时间】:2019-05-06 10:15:45
【问题描述】:

我是 Web 开发的新手,但我有关于 MongoDB 和 Nodejs 驱动程序的问题,给出以下代码:

let MongoClient = require('mongodb').MongoClient;
const url = MY_URL;
const dbConnected = MongoClient.connect(url);
let dbInit =  function (){
    dbConnected.then(
        (client) => {
            let db = client.db('DB_NAME');
            db.dropDatabase()
                .then( () => {})
                .catch( err => { throw err;})
            return client;
        }
    )
    .then(
        (client) =>{
            let db = client.db('knodels');
            db.collection('Users').insertMany([
                //data
            ])
            .then( () => {})
            .catch( err => { throw err;})
            return client;
       }
    )
    .then(
        (client) =>{            
            client.close();
        }
    )
    .catch((err) => {throw err;})
}

我想实现那些事情:

  1. 删除数据库
  2. 删除后创建数据库并填充它
  3. 关闭连接

当我运行函数时,所有这些目标都实现了,但我认为代码有问题:

  • dbInit() 运行时,一些UnhandledPromiseRejectionWarning 被抛出
  • 我猜那些必须异步的承诺的同步肯定有一些时髦
  • 只在最后还是对所有 promise 进行错误捕获?
  • 关闭客户端连接的承诺

【问题讨论】:

    标签: node.js mongodb asynchronous


    【解决方案1】:

    让我们命名一些代码段,

    let dbInit =  function (){
    dbConnected.then(
        (client) => {
            //////////////////////TASK 1/////////////////////
            let db = client.db('DB_NAME');
            db.dropDatabase()
                .then( () => {})
                .catch( err => { throw err;})
            return client;
           //////////////////////TASK 1/////////////////////
        }
    )
    .then(
        (client) =>{
            //////////////////////TASK 2/////////////////////
            let db = client.db('knodels');
            db.collection('Users').insertMany([
                //data
            ])
            .then( () => {})
            .catch( err => { throw err;})
            return client;
            //////////////////////TASK 2/////////////////////
       }
    )
    .then(
        (client) =>{            
            client.close();
        }
    )
    .catch((err) => {throw err;})
    }
    

    在promise链中,和上面的一样,A then 块将在前任 then 被解决后执行。 这意味着包含 TASK 2 的 then 块只会在 TASK 1 完成后执行。

    但是由于您没有TASK 1 返回一个承诺,而是返回一个真实值(变量客户端),并且因为真实值被视为承诺解析。它可能/可能会在删除完成之前开始执行db.collection('Users').insertMany...

    类似的事情将适用于在插入完成之前将调用 client.close 的下一个 then 块。

    因此,与其到处返回客户端,不如返回 db 操作,它是一个承诺,这将使链顺序化。

    你也不需要这样一个嵌套链,每个承诺都有捕获, 像

    let connection = null;
    dbConnected.then((client) => {
      connection = client;  
      const db = client.db('DB_NAME');
      return db.dropDatabase()
    }).then(() => {
      // Perform insert and return a promise//
    }).then(() => {
      return connection.close();
    }).catch((err) => {
       // handle error //
    })
    

    应该做的工作!

    【讨论】:

    • 谢谢你,太清楚了!甚至没有想过使用“全局”变量来解决连接问题。
    猜你喜欢
    • 2017-03-31
    • 1970-01-01
    • 2018-07-14
    • 2019-05-24
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多