Creating Callbacks for required modules in node.js

后端 未结 2 892
别跟我提以往
别跟我提以往 2021-01-07 12:24

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. With

相关标签:
2条回答
  • 2021-01-07 12:52

    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
    
    });
    
    0 讨论(0)
  • 2021-01-07 12:58

    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.

    0 讨论(0)
提交回复
热议问题