async/await 不适用于 mongo DB 查询



工作案例:

当我们调用异步函数并且该函数返回 promise resolve() 时,异步 await 工作正常

不工作的情况:

异步等待不适用于 mongo 数据库查询

try then(), async/await

我有 2 个 JS 文件。

在一个.js文件中,我正在导入函数中的函数.js

工作案例:

当一个.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")
});

当函数.js看起来像

module.exports.functionone = functionone;
async function functionone(email) {
  return await new Promise((resolve, reject) => {
    resolve('need to be done at first')
  });
});

不工作的情况(当需要执行 MONGO DB 查询时):

当一个.js看起来像

var functiononestatus = transactions.functionone(req.session.email).then((came) => {
  console.log(came); // getting undefined
  console.log("exec next")
});

当函数.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])
    });
  });

快速澄清:

  1. .collection('name')返回一个Collection实例,而不是一个承诺,因此无需await它。
  2. toArray() 以两种模式运行:一种在提供函数时使用回调,要么在未提供回调函数时返回 Promise。

在提供回调函数时,您基本上期望 Promise 结果超出toArray(),从而导致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.

然后,用于获取结果的代码:

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

和代码替代,使用回调:

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

注意:首先,我真的需要感谢@mihai Potra的最佳答案。

来吧

案例1:

如果它是一个需要查找文档并从 MongoDb 返回的函数,如 mihai 提到的那样,下面的答案非常酷

const db = <get db somehow>;
async function functionOne(email) {
  const collection = db.collection('allinonestore');
  return collection.find({"email": email}).toArray();
}

案例2:

如果有嵌套函数需要每次返回值,那么据我所知

,这将是最好的

- 不需要每个函数的 async/await 关键字,或者不需要 then()

function one(<parameter>) {
return new Promise(function(resolve, reject) {
const collection = connection.get().collection('<collection_name>');
const docs = collection.find({"Key": Value_fromFunction}).toArray( function (err, result) {
resolve(result[0]);
});

就是这样,在需要时使用解析回调。

最新更新