了解事件驱动编程风格

Understanding Event-Driving Programming Style

寻找这个例子(以及我以前在事件驱动方面的知识)。我可以说这两个例程 运行 独立且并行(所以不会阻塞 hole 程序)。

//....declaration and methods
register_1.on("execut_routine _1", function() { console.log("executed the routine  1"):})
register_2.on("execut_routine _2", function() { console.log("executed the routine  2"):})

但如果我进行此更改:

//....declaration and methods
register_1.on("execut_routine _1", function() { /*Long Blocking Operation*/})
register_2.on("execut_routine _2", function() { /*Long Blocking Operation*/})

第一个触发的事件会阻止第二个事件的发生,对吧?如果是这样,我怎样才能扭转这种影响?

Javascript 是单线程环境,所以除非你正在做 input/output 相关任务(等待文件系统,调用外部资源等),否则你的代码必须等待其他要完成的代码。

使用事件驱动编程风格不会帮助您解决这个问题。

但是,您可以让您的代码进入某种 "sleep" 模式,等待其他代码执行,并在事件循环的下一个滴答时再次开始。 Node.js,例如,使用 process.nextTick(fn) 来注册应该在多个 ticks 上执行的代码。

Javascript [通常] 不是多线程环境,因此即使在您的第一个示例中,实际情况是它们是串行执行的,而不是并行执行的。看起来像 XHR 的 运行 并行,但它们 运行 作为浏览器的功能而不是直接 Javascript (即网络请求 运行 并行),但是 javascript 处理程序将始终连续触发。