xak*_*p35 3 error-handling asynchronous mongoose node.js async-await
在 node.js 中,我有如下代码:
mongoose.connect(dbURI, dbOptions)
.then(() => {
console.log("ok");
},
err => {
console.log('error: '+ err)
}
);
Run Code Online (Sandbox Code Playgroud)
现在我想用 async/await 语法来做。所以我可以从var mcResult = await mongoose.connect(dbURI, dbOptions);,afaik开始,它会等待操作,直到它以任何结果结束(很像调用 C 函数read()或fread()在同步模式下)。
但是我应该怎么写呢?这会返回什么mcResult变量以及如何检查错误或成功?基本上我想要一个类似的片段,但用正确的 async/await 语法编写。
我也想知道因为我有自动重新连接,其中dbOptions:
dbOptions: {
autoReconnect: true,
reconnectTries: 999999999,
reconnectInterval: 3000
}
Run Code Online (Sandbox Code Playgroud)
await如果数据库连接不可用,它会永远“卡住”吗?我希望你能给我一个关于会发生什么以及如何运作的线索。
基本上我想要一个类似的片段,但用正确的 async/await 语法编写。
(async () => {
try {
await mongoose.connect(dbURI, dbOptions)
} catch (err) {
console.log('error: ' + err)
}
})()
Run Code Online (Sandbox Code Playgroud)
请尝试这个,下面的代码具有数据库连接和查询的基础知识:
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));
Run Code Online (Sandbox Code Playgroud)
当我们谈论的async/await时候,我想提一下一些事情 -await绝对需要将其函数声明为async- 否则它会抛出错误。建议将async/await代码包装在try/catch块内。