为node.js中的所需模块创建回调 [英] 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;
主要应用程序
var mymod = require("./mymod.js");
while(!mymod.done)
{
//do some tasks
}
如果有人可以帮助我,我会很高兴。
I would be very glad if someone could help me.
PS:我试过子进程(fork)这种情况,但因为它似乎复制整个过程我不能再访问打开的OpenCV视频捕获...... :(通过使用模块我不会遇到这个问题,但我得到这个为它^^
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 ^^
推荐答案
是的,您可以从模块中进行回调。
Yes, you can have a callback from your module.
它就像
function funcWithCallback(args, callback){
//do stuff
callback();
}
虽然我不知道你想要完成什么,但是循环看起来很可疑。你可能应该从npm投资异步包。
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.
编辑:我觉得有必要澄清一下虽然上面的函数确实打算使用回调而不是返回值,但它并不完全是异步。
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.
这篇关于为node.js中的所需模块创建回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!