简体   繁体   English

异步/等待未按预期顺序执行

[英]Async/await not executing in the expected order

I am currently attempting to learn about MongoDB and asynchronous functions in javascript and have been messing around for the past few hours with no luck. 我目前正在尝试在javascript中学习MongoDB和异步函数,并且在过去的几个小时里一直在搞乱,没有运气。

async function getObj(name) {
  var db = await mongo.connect(DBURL, {
    useNewUrlParser: true
  });

  var dbo = db.db("testdb");

  var meme;

  await dbo.collection("files").findOne({
    "_id": name
  }, function(err, res) {
    console.log(res + " a");
    meme = res;
    console.log(meme + " b");
  });

  console.log(meme + " c");
  await db.close();
  console.log(meme + " d");
  return meme;
}

The program prints it in the order: cdab 程序按顺序打印:cdab

The query works fine where if I do console.log(res), I get the object with the right results so that isn't the problem. 查询工作正常,如果我执行console.log(res),我得到具有正确结果的对象,这不是问题。

Why does the program ignore the await that is before it and end up printing and returning undefined? 为什么程序会忽略它之前的await并最终打印并返回undefined?

You are not using Promises that you can await when you use db.findOne with a callback. 当您将db.findOne与回调一起使用时,您没有使用可以await db.findOne You should await it like so: 你应该这样等待它:

 async function getObj(name) { var db = await mongo.connect(DBURL, { useNewUrlParser: true }); var dbo = db.db("testdb"); var meme = await dbo.collection("files").findOne({ "_id": name }); console.log(meme + " c"); await db.close(); console.log(meme + " d"); return meme; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM