I'm new to Node and JavaScript (well, asynchronous programming in general) and I noticed when I was working on a project that the following code is a circular pattern and that these are bad practice for the obvious reason that the module might not have loaded yet (and the example code is throwing errors because of that).
Here's my code:
Main module
var module2 = require('./module2');
var data = 'data';
module2.fetchStuff(data);
Module2
var module3 = require('./module3');
var cleanDataArray = [];
function fetchStuff(data){
// Fetches stuff based on data
module3.cleanStuff(data);
}
function takeStuffBack(data){
cleanData.push(data);
}
module.exports = {
fetchStuff: fetchStuff,
takeStuffBack: takeStuffBack,
cleanData: cleanDataArray
};
Module3
var module2 = require('./module2');
function cleanStuff(data){
// Clean data from needless stuff
module2.takeStuffBack(data); // I get a TypeError here because `module2` is yet to fully load.
}
module.exports = {
cleanStuff: cleanStuff
};
The XY
What this structure is supposed to do is for the start module
to call a fetching function in module2
, the fetching function needs to "wash" the data in the 3rd module before taking it back and providing it for whatever wants to export it. So I suppose the XY is that I need to do is to get data from a 3rd party API and then "clean" the data from the things it contains but I don't want, and then I need to make that "clean" version available to the rest of the application.
What other ways are there to do this in a better manner, without a circular pattern such as this which is broken because module2
won't load before module3
tries to call it?
data
and calldoSomethingElse
frommodule2
– ratchet freak Aug 3 '15 at 11:43doSomethingElse
should betakeStuffBack
, edited! ThefetchStuff
is containing asynch code so a return wouldn't work – Gemtastic Aug 3 '15 at 11:49