0

My async function either can't access the updated version of the found var, or it's resolving before the async calls are complete. I can't tell what the problem here is, and why it's not working

If tried calling the return true at various different places, and even time delaying it, but inside the handler function it's always empty.

I can't understand why it's not able to access the updated var.

No amount of formatting, or syntax changes seem to fix it.

router.get('/search', (req, res) => {
  var country = req.query.country;
  var found = [];

  var countrySearch = () => {
    if(country==="Worldwide"){return true}
    conf.find({country: { "$regex": country, "$options": "i" }}, function(err, conferences){
      if(found.length!=0){
        for(conference in conferences){
          for(item in found){
            if(found[item]._id!=conferences[conference]._id) 
             found.push(conferences[conference])
          }
        }
        return true;
      }else{
        for(i=0;i<=conferences.length;i++)
          found.push(conferences[i])
        return true;
      }
    })
  }

  function resolve(){
    res.render('index', {list: found});
  }
  async function handler(){
    const place = await countrySearch();
    return resolve();
  }
  handler();

})

If console.log the output of found after pushing to it, inside the Async function, it returns correctly with the appended items.

When passing it to Pug as a variable, and anywhere inside the resolve function, the found var appears empty.

Solved.

Function != Promise;

var countrySearch = conf.find({country: { "$regex": country, "$options": "i" }}, function(err, conferences){
    if(country==="Worldwide"){return true}
    if(found.length!=0){
      for(conference in conferences){
        for(item in found){
          if(found[item]._id!=conferences[conference]._id) found.push(conferences[conference])
        }
      }
      return true;
    }else{
      for(i=0;i<=conferences.length;i++){
        found.push(conferences[i])
        if(i===conferences.length) return true;
      }
    }
  })
  • It would be helpful if you remove as much code as possible to make it easier to help you! – wiesson Aug 05 '19 at 18:32
  • 3
    Neither of your `countrySearch()`, `titleSearch()` or `monthSearch()` returns a promise that could be awaited. You are `await`ing the `undefined` return value, which happens immediately. `await` doesn't magically know that you called an asynchronous function with a callback. – Bergi Aug 05 '19 at 18:34
  • Oh right. I'm retarded! – user1429671 Aug 05 '19 at 18:40
  • Thank you! For anyone else having a blonde moment see above. – user1429671 Aug 05 '19 at 18:41

0 Answers0