如何对猫鼬使用异步/等待

时间:2019-02-26 17:01:43

标签: node.js asynchronous mongoose error-handling async-await

在node.js中,我有如下代码:

mongoose.connect(dbURI, dbOptions)
.then(() => {
        console.log("ok");
    },
    err => { 
        console.log('error: '+ err)
    }
);

现在,我想使用异步/等待语法。因此,我可以从var mcResult = await mongoose.connect(dbURI, dbOptions);开始,然后它会等待操作,直到以任何结果结束(就像在同步模式下调用C函数read()fread()一样)。

那我该写些什么呢?返回到mcResult变量的内容是什么,以及如何检查错误或成功?基本上,我想要一个类似的代码段,但是要使用正确的async / await语法编写。

我还想知道,因为我在dbOptions中具有自动重新连接的功能:

dbOptions: {
  autoReconnect: true,
  reconnectTries: 999999999,
  reconnectInterval: 3000
}

万一数据库连接不可用,它会永远“塞在” await上吗?希望您能给我一个线索,以了解会发生什么以及如何运作。

3 个答案:

答案 0 :(得分:2)

请尝试一下,下面的代码具有数据库连接和查询的基础:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let url = 'mongodb://localhost:27017/test';

const usersSchema = new Schema({
    any: {}
}, {
    strict: false
});

const Users = mongoose.model('users', usersSchema, 'users');

/** We've created schema as in mongoose you need schemas for your collections to do operations on them */

const dbConnect = async () => {
    let db = null;
    try {
        /** In real-time you'll split DB connection(into another file) away from DB calls */
        await mongoose.connect(url, { useNewUrlParser: true }); // await on a step makes process to wait until it's done/ err'd out.
        db = mongoose.connection;

        let dbResp = await Users.find({}).lean(); /** Gets all documents out of users collection. 
                                   Using .lean() to convert MongoDB documents to raw Js objects for accessing further. */

        db.close(); // Needs to close connection, In general you don't close & re-create often. But needed for test scripts - You might use connection pooling in real-time. 
        return dbResp;
    } catch (err) {
        (db) && db.close(); /** Needs to close connection -
                   Only if mongoose.connect() is success & fails after it, as db connection is established by then. */

        console.log('Error at dbConnect ::', err)
        throw err;
    }
}

dbConnect().then(res => console.log('Printing at callee ::', res)).catch(err => console.log('Err at Call ::', err));

在我们谈论async/await时,我想提及的几件事-await绝对需要将其函数声明为async-否则会引发错误。并且建议将async/await代码包装在try/catch块中。

答案 1 :(得分:1)

  

基本上,我需要一个类似的代码段,但要使用正确的async / await语法编写。

(async () => {
  try {
    await mongoose.connect(dbURI, dbOptions)
  } catch (err) {
    console.log('error: ' + err)
  }
})()

答案 2 :(得分:0)

const connectDb = async () => {
    await mongoose.connect(dbUri, dbOptions).then(
        () => {
            console.info(`Connected to database`)
        },
        error => {
            console.error(`Connection error: ${error.stack}`)
            process.exit(1)
        }
    )
}

connectDb().catch(error => console.error(error))

让我们假设禁止使用then(),您可以这样做...

const connectDb = async () => {
    try {
        await mongoose.connect(dbConfig.url, dbConfigOptions)

        console.info(`Connected to database on Worker process: ${process.pid}`)
    } catch (error) {
        console.error(`Connection error: ${error.stack} on Worker process: ${process.pid}`)
        process.exit(1)
    }
}