1 javascript mongodb node.js promise async-await
工作案例:
当我们调用异步函数并且该函数返回承诺 resolve() 时,异步等待工作正常
不工作的情况:
异步等待不适用于 mongo DB 查询
试过 then(), async/await
我有 2 个 JS 文件。
在 one.js 文件中,我正在导入 functionone.js 中的函数
工作案例:
当 one.js 看起来像
var functiononestatus = transactions.functionone(req.session.email).then((came) => {
console.log(came); // getting `need to be done at first` message
console.log("exec next")
});
Run Code Online (Sandbox Code Playgroud)
当 functionone.js 看起来像
module.exports.functionone = functionone;
async function functionone(email) {
return await new Promise((resolve, reject) => {
resolve('need to be done at first')
});
});
Run Code Online (Sandbox Code Playgroud)
非工作情况(当需要执行 mongo db 查询时):
当 one.js 看起来像
var functiononestatus = transactions.functionone(req.session.email).then((came) => {
console.log(came); // getting undefined
console.log("exec next")
});
Run Code Online (Sandbox Code Playgroud)
当 functionone.js 看起来像
module.exports.functionone = functionone;
async function functionone(email) {
//mongo starts
var collection = await connection.get().collection('allinonestores');
await collection.find({
"email": email
}).toArray(async function(err, wallcheck) {
return await new Promise((resolve, reject) => {
resolve(wallcheck[0])
});
});
Run Code Online (Sandbox Code Playgroud)
小智 5
快速澄清:
.collection('name')返回一个Collection实例,而不是一个 Promise,所以不需要await它。toArray() 以两种模式运行:要么在提供函数时使用回调,要么在未提供回调函数时返回 Promise。toArray()在提供回调函数时,您本质上是在期待 Promise 结果,结果是undefined,因为由于 toArray() 的双重操作模式,回调优先并且没有返回任何承诺。
此外,toArray(callback)不将async函数作为回调。
以下是用于检索集合的代码的外观:
const client = await MongoClient.connect('your mongodb url');
const db = client.db('your database name'); // No await here, because it returns a Db instance.
const collection = db.collection('allinonestores'); // No await here, because it returns a Collection instance.
Run Code Online (Sandbox Code Playgroud)
然后,获取结果的代码:
const db = <get db somehow>;
// You could even ditch the "async" keyword here,
// because you do not do/need any awaits inside the function.
// toArray() without a callback function argument already returns a promise.
async function functionOne(email) {
// Returns a Collection instance, not a Promise, so no need for await.
const collection = db.collection('allinonestore');
// Without a callback, toArray() returns a Promise.
// Because our functionOne is an "async" function, you do not need "await" for the return value.
return collection.find({"email": email}).toArray();
}
Run Code Online (Sandbox Code Playgroud)
和代码替代,使用回调:
const db = <get db somehow>;
// You could even ditch the "async" keyword here,
// because you do not do/need any awaits inside the function.
// You're forced to return a new Promise, in order to wrap the callback
// handling inside it
async function functionOne(email) {
// Returns a Collection instance, not a Promise, so no need for await.
const collection = db.collection('allinonestore');
// We need to create the promise outside the callback here.
return new Promise((resolve, reject) => {
db.find({"email": email}).toArray(function toArrayCallback(err, documents) {
if (!err) {
// No error occurred, so we can solve the promise now.
resolve(documents);
} else {
// Failed to execute the find query OR fetching results as array someway failed.
// Reject the promise.
reject(err);
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5393 次 |
| 最近记录: |