0

I'm sure I'm missing something very basic around async functions or something, but when I try and access a function in a module the result is not available.

This is the code in the main file, the module is accessed as 'queries'.

app.post('/records', (req,res) => {
  const query = req.body.query;
  const queryresult = queries.runSearch(query);
  res.end(queryresult);
});

The code for runSearch is the following


function runSearch(query){

  var MongoClient = require('mongodb').MongoClient;
  var url = "mongodb://localhost:27017/";

  MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    console.log("Connected!");

    var dbo = db.db("followers");
    dbo.collection("User").find({Bio : {$regex : query}}).toArray(function(err, result) {
      if (err) throw err;

      console.log("records returned = " + result.length);
      
      var JSONResult = JSON.stringify(result);

      db.close();
      console.log('db connection closed');

      return JSONResult;
    });

  });

}

module.exports = {runSearch}

I get what's happening is the async Mongo call is working away and not being waited for. I've read everything around async / await but it melts my brain a bit.

Would love to know what it might look like with this code.

  • 2
    There isn't enough information in the question to know what the answer is. What follows is a guess. Assuming `runSearch` returns a promise, and `res.end` accepts the result after awaiting the promise then a possible solution might be to get the value when the promise resolves: `queries.runSearch(query).then(queryresult => res.end(queryresult))` What does `runSearch` return? What do you want `queryresult` to be and what is it? – YouCodeThings Jul 31 '22 at 20:34
  • 1
    @YouCodeThings I'm pretty certain the OP wouldn't have this problem if they knew about and were using promises - my bet is on the function returning `undefined` :-) – Bergi Jul 31 '22 at 20:36
  • 1
    Since you mentioned a mongodb query, which is asynchronous, I've given you a pointer to our canonical Q&A on the topic. Please read its answers and try to apply them to your situation. If you need specific help with your case, please [edit] your question to include the definition of `runSearch`, and ideally your attempts at using promises or callbacks. (Btw, this has nothing to do at all with the function being defined in a separate module) – Bergi Jul 31 '22 at 20:38
  • Can you show us how you attempted to use `async`/`await`? Also if you're new to this, you might want to use a callback first (`function runSearch(query, callback){`, `callback(JSONResult)`), then learn about promises. – Bergi Jul 31 '22 at 20:58
  • Thanks @Bergi really appreciate it. I've been struggling to wrap my head around callbacks and async generally. Think I'd like to start with the simple callback - I've edited the code to show what it currently shows, not quite sure how to turn runSearch into a callback though. – halfiranian Aug 01 '22 at 07:05
  • 1
    Ok amazing got it working, thanks guys. Here's what I did, create a promise in the main function and then use your suggestion @YouCodeThings to use .then to get results big thank you for the help – halfiranian Aug 01 '22 at 11:11

0 Answers0