First of all, problem is not about requiring something and it is not related to scope. What is actually happening is, as already stated by others, finddata
is asynchronous function meaning that you don't know at what time in future callback function (resp) {...}
will be invoked and when val
be something other than null
. To tackle this you need either to pass additional callback to get
function, or to return a promise from get
function. Cleaner approach would be to return Promise from get
function.
x.get()
.then(() => {
// val is ready
})
or
x.get(() => {
// val is ready
})
Another problem that you have is that you are not taking into account what if finddata
invokes your callback with an error? Having something like:
finddata('/', function(resp){
that.val = resp
}
Is really something what you don't want to have. With code that you have, if finddata
invokes your callback with an error
, val
would be equal to that error, otherwise it would be equal to null
, if finddata
complies to node best practices to invoke callback with null
if there was no errors, such as cb(null, data)
.
Besides that what you are trying to do? Is there a need for exposing module with val
thing? Is get
function meant to be called regularly from app? If so why introducing new module, just call finddata
which is i guess module by itself already.