Understanding module.exports with a callback

I have a situation where I create a node module that returns only after the asynchronous operation is completed. One way to do this (shown below) is to assign module.exports a function with a callback parameter. Inside the function, you will then return the callback.

Here is an example of what I am describing with a completed callback:

// module called test.js
module.exports = function(done) {
  // do something asynchronous here
  process.nextTick(function() {
    done();  //  call done when the asynchronous thing is complete...
  }
}

Where I hung up is how the callback is made, given that I don't define it anywhere ...

For example, in javascript in vanilla, I can pass it as a parameter and then call it inside the function while I create the callback function in the call.

function testAsyncCb(msg, done) {
  console.log(msg);
  setTimeout( function() {
    done();
  }, 1000);
  console.log("last line in code");
}

testAsyncCb("testing", function(){ console.log("done"); });  // invocation with callback function

Back in the first node example, somewhere calling module.exports using require () creates a function for done () to get the solution right? If not, how is callback resolved?

, . / .

+4
1

module.exports (module.exports = {}). , , , .

,

 module.exports = function myFunc() {} 

,

var abc = require('./my-module'); --> abc == myFunc

module.export.myFunc = function () {}

var abc = require('./my-module'); --> abc == {myFunc: function () {}}

sync, async, requirejs ( AMD, commonjs).

. http://www.sitepoint.com/understanding-module-exports-exports-node-js/ nodejs: https://nodejs.org/api/modules.html

+6

Source: https://habr.com/ru/post/1611823/


All Articles