通过回调了解 module.exports
understanding module.exports with callback
我有这样一种情况,我正在创建一个 return 只有在异步操作完成时才会出现的节点模块。一种方法(如下所示)是分配 module.exports 一个带有回调参数的函数。在函数内部,您将 return 回调。
这是我描述的一个例子,done 是回调:
// module called test.js
module.exports = function(done) {
// do something asynchronous here
process.nextTick(function() {
done(); // call done when the asynchronous thing is complete...
}
}
我被挂断的地方在于回调 done 确实是如何执行的,考虑到我没有在任何地方定义它...
例如,在 vanilla javascript 中,我可以将 done 作为参数传递,然后在函数中调用它,只要我在调用中创建回调函数即可。
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
回到第一个节点示例,某处 require() 对 module.exports 的调用正在为 done() 创建一个函数以解析为正确?如果不是,回调是如何解决的?
很难找到有关其工作原理的信息。任何 help/direction 表示赞赏。
将 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 () {}}
要求操作是同步的,而不是像 requirejs 中的异步(意思不是 AMD 但更像 commonjs)。
见http://www.sitepoint.com/understanding-module-exports-exports-node-js/
了解更多信息
也适用于 nodejs 官方文档:https://nodejs.org/api/modules.html
我有这样一种情况,我正在创建一个 return 只有在异步操作完成时才会出现的节点模块。一种方法(如下所示)是分配 module.exports 一个带有回调参数的函数。在函数内部,您将 return 回调。
这是我描述的一个例子,done 是回调:
// module called test.js
module.exports = function(done) {
// do something asynchronous here
process.nextTick(function() {
done(); // call done when the asynchronous thing is complete...
}
}
我被挂断的地方在于回调 done 确实是如何执行的,考虑到我没有在任何地方定义它...
例如,在 vanilla javascript 中,我可以将 done 作为参数传递,然后在函数中调用它,只要我在调用中创建回调函数即可。
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
回到第一个节点示例,某处 require() 对 module.exports 的调用正在为 done() 创建一个函数以解析为正确?如果不是,回调是如何解决的?
很难找到有关其工作原理的信息。任何 help/direction 表示赞赏。
将 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 () {}}
要求操作是同步的,而不是像 requirejs 中的异步(意思不是 AMD 但更像 commonjs)。
见http://www.sitepoint.com/understanding-module-exports-exports-node-js/ 了解更多信息 也适用于 nodejs 官方文档:https://nodejs.org/api/modules.html