Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  173] [ 4]  / answers: 1 / hits: 97498  / 7 Years ago, wed, september 27, 2017, 12:00:00

I'm trying to get the hang of using Mongoose promises with the async/await functionality of Node.js. When my function printEmployees is called I want to save the list of employees which are queried by the orderEmployees function. While, the console.log statement inside orderEmployees returns the expected query, the console.log inside of printEmployees returns undefined, suggesting that I'm not returning the promise correctly.



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

More From » node.js

 Answers
4

You need to return your Promise.



  • Currently, you are awaiting on a function that returns undefined.

  • await only actually "waits" for the value if it's used with a Promise.

  • Always keep in mind that you can only await Promises or async functions, which implicitly return a Promise1.




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

Also really important, you should throw instead of return in your .catch handler. Returning from within a .catch handler will cause the promise chain to trigger it's .then instead of it's .catch thus breaking the error handling chain.


Better yet, don't include .catch at all and let the the actual error bubble up the promise chain, instead of overriding it with your own non-descriptive 'error occured' message.


Error conditions should throw the error, not return it.




1 You can also await non-Promises, but only for values that are evaluated synchronously.


[#56370] Monday, September 25, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;