On my learning journey, I have started to look at modules for javaScript/Node. What is confusing me is how to return information from a module when the time to complete the functions within a module is unknown.
This returns as expected:
controller.js
const myModule = require('./myModule');
var myWord = myModule.myExp();
console.log(myWord); //returns "Hello World"
myModule.js
module.exports = {
myExp: function(){
return mytimeOut();
}
}
function mytimeOut(){
var myWord = "Hello World";
return myWord;
}
What I cannot seem to grasp, is the best way to return myModule when there is an indefinite time to bring back the required result.
How do I get the controller to show "Hello World" and not "Undefined" in the example below. I have read about callbacks, promises, async/await - but without any over-complications, I cannot seem to find a simple solution for this.
controller.js
const myModule = require('./myModule');
var myWord = myModule.myExp();
console.log(myWord); //returns undefined
myModule.js
module.exports = {
myExp: function(){
return mytimeOut();
}
}
function mytimeOut(){
setTimeout(() => {
myWord = "Hello World";
return myWord;
}, 5000);
}