0

I did the test below for a seed that needs to get data from the model User. I think my problem here is that testFunction is returning name before it's value is updated within the .then().

I clearly don't understand how the flow is working here. Anybody has an idea about why is this happening and how could I solve it? Thank in advance ;)

const testFunction = () => {

let name = undefined

User.find()
    .then(result => name = result[0].username)
    .catch(err => console.log(err))

return name }
Aretius
  • 7
  • 3
  • You need to convert `testFunction` to be `async` and then you can `await` like so: ```let results = User.find()```. – dwosk Oct 02 '20 at 22:34

1 Answers1

0

Convert your function to be async and then you will be able to await the results of your mongoose call. For example:

const testFunction = async () => {
  let name = undefined;
  let results = await User.find();

  if (results && results[0] && results[0].username) {
    name = results[0].username
  } else {
    // handle error
  }

  return name;
}
dwosk
  • 1,202
  • 8
  • 11
  • Hi dwosk! Thank you. I could handle the problem thanks to your answer. But I have some questions. Why when I call _testFunction()_ it returns me a promise? And what are the if else from the function are to? I realized that removing them returns a name undefined but if I console.log(results) before the if statement there is already data. So I don't see the point to use the if statement. Thanks again! – Aretius Oct 02 '20 at 23:14
  • I recommend you read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function. When you mark it as `async` it returns a promise. The if/else block is a type guard so you don't try to access the `username` property of a null, which will throw an exception. I put it in there just to be safe. – dwosk Oct 02 '20 at 23:18