user2267175 user2267175 - 4 months ago 7
Node.js Question

Can you call a function in your main node.js server file from within a module file without a callBack?

Question is as title describes,
Can you call a function in your main node.js server file from within a module file without a callBack?
And, if that is not possible, can you use a callBack in a interval and call it multiple times?

Example code:

//Main server.js file
var moduleFile = require('./mFile');
...

var foobar = moduleFile.addFoobar();

if(foobar) foobar.fooReady();

function foo(bar){
//do something.
}


//moduleFile / mFile.js

var foobars = [];

function Foobar(){
this.id = 0;

Foobar.prototype.fooReady = function(){
setInterval( function(){
//call foo(); in main file..?
}, 1000);
}

}

var addFoobar = function(data) {
var foobar = new Foobar();
foobar.id = foobars.length+1;

foobars.push(foobar);
return foobar;
}

module.exports.foobars = foobars;
module.exports.addFoobar = addFoobar;


EDIT:

If the above isn't possible, would it be possible to do it with a callback by changing the following lines..

//main server.js
if(foobar) foobar.fooReady(foo);

//mFile.js
Foobar.prototype.fooReady = function(callback){
setInterval( function(){
//can you call foo(); in main file via callback(); on every interval run?
}, 1000);
}


Cheers.

Answer

Can you call a function in your main node.js server file from within a module file without a callBack?

Yes, you can call synchronous functions in other modules without a callback. That's just like calling Math.max() or any plain function in Javascript.

can you use a callBack in a interval and call it multiple times?

Yes, you can.

Callbacks are used for a variety of reasons. For example, Array.prototype.map() uses a callback that is designed to be called synchronously many times and that's a perfectly acceptable way to use a callback.

Callbacks are also used to signify the completion of an asynchronous operation. In that case, they are usually only called once to signify completion.

But, setInterval() itself uses an asynchronous callback that is designed to get called many times. So, you can certainly design one that way too.


What's important is that your design is clear so the caller knows exactly what to expect. Is it called once or more than once? Is it called synchronously or asynchronously? All are appropriate in some situations as long as the caller knows what to expect.


You can certainly use a callback for your interval like this:

//main server.js
if(foobar) foobar.fooReady(foo);

//mFile.js
Foobar.prototype.fooReady = function(callback){
    setInterval( function(){
        callback();
    }, 1000);
 }

Or, if there's nothing else going on in the interval, it would even just be this:

//mFile.js
Foobar.prototype.fooReady = function(callback){
    setInterval(callback, 1000);
 }
Comments