javascript 在 node.js 中为所需模块创建回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18382186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating Callbacks for required modules in node.js
提问by Fidel90
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 ^^
PS:我在这种情况下尝试了子进程(fork),但由于它似乎复制了整个过程,我无法再访问打开的 OpenCV 视频捕获... :( 通过使用模块,我没有遇到这个问题,但我得到了这个一个吧^^
回答by Josh C.
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.
虽然我不知道您要完成什么,但 while 循环看起来很可疑。您可能应该投资 npm 的 async 包。
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.
这允许被调用的函数退出并将该函数的逻辑的执行推迟到下一个滴答声。
回答by Or Ron
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
});