Javascript 使用带有 async/await 的 mongoose 承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46457071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:26:42  来源:igfitidea点击:

Using mongoose promises with async/await

javascriptnode.jsasynchronouspromise

提问by Patrick Connors

I'm trying to get the hang of using Mongoose promises with the async/await functionality of Node.js. When my function printEmployeesis called I want to save the list of employees which are queried by the orderEmployeesfunction. While, the console.logstatement inside orderEmployeesreturns the expected query, the console.loginside of printEmployeesreturns undefined, suggesting that I'm not returning the promise correctly.

我正在尝试使用带有 Node.js 的异步/等待功能的 Mongoose 承诺。当我的函数printEmployees被调用时,我想保存该orderEmployees函数查询的员工列表。而console.log里面的语句orderEmployees返回了预期的查询,即返回的console.log内部,表明我没有正确返回承诺。printEmployeesundefined

I'm new to promises so entirely possible that I'm not correctly understanding the paradigm... any help is much appreciated.

我对承诺非常陌生,以至于我没有正确理解范式……非常感谢任何帮助。

  printEmployees: async(company) => {
    var employees = await self.orderEmployees(company);
    // SECOND CONSOLE.LOG
    console.log(employees);
  },

  orderEmployees: (companyID) => {
    User.find({company:companyID})
    .exec()
    .then((employees) => {
      // FIRST CONSOLE.LOG
      console.log(employees);
      return employees;
    })
    .catch((err) => {
      return 'error occured';
    });
  },

采纳答案by nicholaswmin

You need to returnyour Promise, otherwise you are awaiting on a function that returns undefined.

你需要return你的Promise,否则你正在等待一个返回的函数undefined

orderEmployees: (companyID) => {
  return User.find({ company:companyID }).exec()
}

Currently, you're awaiting a non-Promise so next-line code will run immediately; before the Promise you really want to await actually resolves.

目前,您正在等待一个非 Promise,因此下一行代码将立即运行;在您真正想要等待的 Promise 真正解决之前。

Also really important, you should throwinstead of returnin your .catchhandler. Or better yet, don't include .catchat all and let the the actual error bubble up the promise chain, instead of overriding it with your own non-descriptive 'error occured'message.

同样非常重要的是,您应该throw而不是return在您的.catch处理程序中。或者更好的是,根本不要包含.catch并让实际错误在承诺链中冒泡,而不是用您自己的非描述性'error occured'消息覆盖它。

回答by Tamas Hegedus

In order to make orderEmployeesbehave like async functions, you have to return the resulting promise. There are two rules to follow when using promises without async/awaitkeywords:

为了使orderEmployees行为像异步函数,您必须返回结果承诺。使用不带async/await关键字的promise 时需要遵循两条规则:

  1. A function is asynchronous if it returns a Promise
  2. If you have a promise (for example returned by an async function) you must either call .thenon it or return it.
  1. 一个函数是异步的,如果它返回一个 Promise
  2. 如果您有一个承诺(例如由异步函数返回),您必须调用.then它或返回它。

When you are using async/awaitthen you mustawaiton promises you obtain.

当您使用时,async/await必须遵守await您获得的承诺。

This said you will notice that you do not return the promise generated inside orderEmployees. Easy to fix, but its also easy to rewrite that function to async too.

这表示您会注意到您没有返回内部生成的承诺orderEmployees。易于修复,但也很容易将该函数重写为异步。

orderEmployees: (companyID) => {
  return User.find({company:companyID}) // Notice the return here
  .exec()
  .then((employees) => {
    // FIRST CONSOLE.LOG
    console.log(employees);
    return employees;
  })
  .catch((err) => {
    return 'error occured';
  });
},

or

或者

orderEmployees: async(companyID) => {
  try {
    const employees = await User.find({company:companyID}).exec();
    console.log(employees);
    return employees;
  } catch (err) {
    return 'error occured';
  }
},

PS: the error handling is somewhat flawed here. We usually do not handle errors by returning an error string from a function. It is better to have the error propagate in this case, and handle it from some top-level, UI code.

PS:这里的错误处理有点缺陷。我们通常不会通过从函数返回错误字符串来处理错误。在这种情况下最好让错误传播,并从一些顶级 UI 代码处理它。

回答by barnski

You are not returning a Promise from orderEmployees.

您不会从 orderEmployees 返回 Promise。

printEmployees: async(company) => {
  var employees = await self.orderEmployees(company);
  // SECOND CONSOLE.LOG
  console.log(employees);
},

orderEmployees: (companyID) => {
  return User.find({company:companyID})
 .exec()
 .then((employees) => {
   // FIRST CONSOLE.LOG
   console.log(employees);
   return employees;
 })
 .catch((err) => {
   return 'error occured';
 });
},

回答by James

You need to return a Promisefrom orderEmployees

你需要PromiseorderEmployees

orderEmployees: companyId => User.find({ companyId }).exec()

If you want to do some error handling or pre-processing before you return then you can keep your code as is but just remember to return the result (promises are chainable).

如果您想在返回之前进行一些错误处理或预处理,那么您可以保持代码不变,但请记住返回结果(promise 是可链接的)。