Reputation: 53
I am getting undefined in console.log. Why? How to correct it and, I have to do it on this why only.
This is code for demofile:
exports.selectorquery = function() {
var conn = "New connection";
var nt = "Last Connect";
function myFunc(arg) {
return conn;
}
setTimeout(myFunc, 3500, 'funky');
}
This is for run.js:
var go = require('./demofile.js');
console.log(go.selectorquery());
Upvotes: 2
Views: 45
Reputation: 12089
Your selectorquery
function does not return anything. Therefore, undefined is returned.
The function myFunc
is scheduled for execution later but your console log will log the result of selectorquery
, which is undefined.
Adding a console log to myFunc
will log after the specified timeout:
function myFunc(arg) {
console.log(conn);
return conn;
}
Upvotes: 0
Reputation: 5003
YOur function is not returning anything:
Here's how you can do it.
demofile.js
exports.selectorquery = function (callback) {
var conn = "New connection";
var nt = "Last Connect";
function myFunc(arg) {
callback(null, conn);
}
setTimeout(myFunc, 3500, 'funky');
}
run.js
const go = require('./demofile');
go.selectorquery(function(err, data) {
console.log(data);
});
Now run:
node run.js
It should log
New connection
Read more: NodeJS Export and Import Modules
Hope it solved your query.
Upvotes: 1