0

I'm newish i want to get to my app.js from a search.js an object. Inside the module works fine but when i acces from outside i get undefined value app.js

const search = require(__dirname + "/search.js");
app.get("/",  function(req, res) {
var list = search.foundType(TypeProduct);
console.log(list);
res.render("home",{listType: list});
});

search.js

exports.foundType = function(TypeProduct) {
  TypeProduct.find({}, function(err, listOfProduct) {
    if (!err) {
      if (listOfProduct) {
        return listOfProduct;
      }
    } else {
      console.log(err);
    }
  });
}

I will appreciate the help.

Gabriel
  • 15
  • 3
  • 1
    `foundType` uses `TypeProduct` which is a callback based function, you'll need to either provide a callback to get the result, or to wrap the function on in a Promise. I'd recommend reviewing MDN's [asynchronous JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous) article to get a handle on some of the fundamentals. This was hard for me to wrap my head around at first! – Nick Tomlin Feb 01 '21 at 16:41
  • Thanks i will give it a try – Gabriel Feb 01 '21 at 17:17
  • @NickTomlin can you give an example beacause a read it but i donde get it – Gabriel Feb 01 '21 at 19:46
  • Hi @Gabriel, welcome to SO, have you checked https://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js? – Hoang Dao Feb 02 '21 at 05:20
  • Hi @HoangDao i read it but ... my module is working fine inside the module i see the query but... in the app.js gets undefined im trying to use promise but only i get is pending my head hurts hehehehehe – Gabriel Feb 02 '21 at 15:03
  • @Gabriel I see, then Nick's answer will solve your problem – Hoang Dao Feb 03 '21 at 03:22

1 Answers1

2

TypeProduct.find is a function that takes in another function. It does some work (that may be asynchronous) and then calls that function with the result: a list of products. The return value of TypeProduct.find is undefined because that is the default for a JavaScript function that does not explicitly return a value.

You can see what is happening in this similar snippet:

function myAsyncFunction (callback) {
   setTimeout(function () { callback([1, 2, 3]) }, 1000)
   return undefined
}

function callback (results) {
  console.log("received async results: " + results)
}

const returnFromFunction = myAsyncFunction(callback)
console.log("return from function:" + returnFromFunction)

What you need to do is provide a callback to find and then finish responding to the http request within it:

app.get("/",  function(req, res) {
  search.foundType(TypeProduct, function (list) {
    res.render("home",{listType: list});
  });
});

I know this is difficult to grasp at first. Don't worry, you'll get it! You can read more in this article about async callbacks

Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90