0

I'm writing a function that pass in a string called "term" to search in my MongoDB, then add its results to an existed empty array of results called "result[]":

var searchAndAddToResults = (result, term)=> {
  Place.find({ $or: [
    {name: term}, {category: term}
  ] }, places=> {
    for (let i in places) {
      if (!itemExists(result, places[i].toObject())) {
        result.push(places[i].toObject())
      }
    }
    console.log(result)   // result isn't empty, which is good
  })
  console.log(result)   // result is empty, which is bad and weird
  return result    // this returned result is also empty, THIS is the real problem
}

Can anyone help me with restructuring this code to get it work? Thanks

thousight
  • 1,134
  • 1
  • 14
  • 39
  • The find operation is asynchronous, so when you make the request, the console.log outside the callback is called immediately, before the find returns any results. – kinakuta Jun 24 '16 at 03:11
  • I can tell that, but the problem is how to make sure my returned result value is correct instead of being empty? – thousight Jun 24 '16 at 03:17
  • That's because you're returning synchronously - return a promise instead. – kinakuta Jun 24 '16 at 07:24

1 Answers1

0

These calls are asynchronous - which is why you are getting results in succcess callback of Place.find() and finding one outside of the method. Because as soon as Place.find() is called the next line is executed. So it'll be great if you learn to work with these asynchronous calls of javascript.

Nafiul Islam
  • 1,220
  • 8
  • 20
  • but the problem is my returned result is also empty – thousight Jun 24 '16 at 03:15
  • I think this is a great place where you'll get different scenarios and answers on how to processing results in an asynchronous call - http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Nafiul Islam Jun 24 '16 at 03:18