簡體   English   中英

如何在貓鼬中使用異步/等待

[英]How to use async/await with mongoose

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

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

現在我想用 async/await 語法來做。 所以我可以從var mcResult = await mongoose.connect(dbURI, dbOptions); , afaik 它將等待操作,直到它以任何結果結束(很像在同步模式下調用 C 函數read()fread() )。

但是我應該怎么寫呢? 這會返回什么mcResult變量以及如何檢查錯誤或成功? 基本上我想要一個類似的片段,但用正確的 async/await 語法編寫。

我也想知道因為我有自動重新連接,在dbOptions

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

如果數據庫連接不可用,它會永遠“卡住” await嗎? 我希望你能給我一個關於會發生什么以及如何運作的線索。

基本上我想要一個類似的片段,但用正確的 async/await 語法編寫。

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

請試試這個,下面的代碼包含數據庫連接和查詢的基礎知識:

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塊中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM