Creating Callbacks for required modules in node.js

Is there any possibilitie for creating some kind of a callback within a module created by my own?

My problem is that I have written a module for my application. Within this module is done some task and now my main-app should get a feedback that the module finished his task.

The following describes what i want but wont work ofcourse...

//module mymod.js
function start()
{
    var done = false;

    //do some tasks
    done = true;
}
exports.done = done;

Main App

var mymod = require("./mymod.js");

while(!mymod.done)
{
    //do some tasks
}

I would be very glad if someone could help me.

PS: I tried out child processes (fork) for this situation but as it seems to copy the whole process I cant access opened OpenCV video captures anymore... :( By using modules I dont run into this problem, but instead I get this one for it ^^

Answers:

Answer

Yes, you can have a callback from your module.

It's as simple as

function funcWithCallback(args, callback){
    //do stuff

    callback();
}

While I don't know what you are trying to accomplish, the while loop looks suspicious. You probably should invest in the async package from npm.

async on github

EDIT: I felt the need to clarify something. While the above function does in fact intend the callback is used instead of the return value, it's not exactly async.

The true async approach is to do something like this:

function funcWithCallback(args, callback){      
    process.nextTick(function() {
        //do stuff
        callback();
    });     
}

This allows the called function to exit and defers the execution of the logic of that function until the next tick.

Answer

The call back syntax:

function start(callback)
{


    //do some tasks

    callback(data);
}

exports.start = start;

Anywhere you require your module:

var mymod = require("./mymod.js");

mymod.start(function(data) {
   //do some tasks , process data

});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.