首页 > Web开发 > 详细

node.js 的事件驱动

时间:2019-09-14 12:11:34      阅读:75      评论:0      收藏:0      [点我收藏+]

照抄自Understanding node.js

Node is basically very good when you need to do several things at the same time. Have you ever written a piece of code and said "I wish this would run in parallel"? Well, in node everything runs in parallel, except your code.

当你需要同时做几件事时,Node基本上非常好。你有没有写过一段代码并说“我希望这会并行运行”? 在node中除了代码,所有的东西都是并行的。

"Huh?"
That‘s right, everything runs in parallel, except your code. To understand that, imagine your code is the king, and node is his army of servants.

想象你的代码是大哥,node是他的马仔。

The day starts by one servant waking up the king and asking him if he needs anything. The king gives the servant a list of tasks and goes back to sleep a little longer. The servant now distributes those tasks among his colleagues and they get to work.

这天马仔叫醒大哥并问他有什么需要做的。大哥给出一份任务清单然后继续睡觉去liao,马仔把任务分配给其他马仔一起去执行。

Once a servant finishes a task, he lines up outside the kings quarter to report. The king lets one servant in at a time, and listens to things he reports. Sometimes the king will give the servant more tasks on the way out.
Life is good, for the king‘s servants carry out all of his tasks in parallel, but only report with one result at a time, so the king can focus. *

每当一个马仔收完保护费,他就会在大哥房外排队向大哥报告,每次大哥只听一个马仔汇报工作情况,有时候汇报完在马仔出门前还会给马仔在安排别的任务(即回调,给大嫂买包包之类的)

"That‘s fantastic, but could you quit the silly metaphor and speak geek to me?"
Sure. A simple node program may look like this:

用下面这个代码段解释一下

var fs = require('fs')
  , sys = require('sys');

fs.readFile('treasure-chamber-report.txt', function(report) {
  sys.puts("oh, look at all my money: "+report);
});

fs.writeFile('letter-to-princess.txt', '...', function() {
  sys.puts("can't wait to hear back from her!");
});

Your code gives node the two tasks to read and write a file, and then goes to sleep. Once node has completed a task, the callback for it is fired. But there can only be one callback firing at the same time. Until that callback has finished executing, all other callbacks have to wait in line. In addition to that, there is no guarantee on the order in which the callbacks will fire.

这段代码让node去读和写两个任务,然后node就继续睡觉去了。直到有一个任务完成,触发了他的回调,但是同时只能有一个回调函数执行(剩余的回调函数会排成一个队列,按顺序一个一个执行)。因为任务是并行执行的,无法保证回调函数触发的顺序(这就是所谓回调地狱的原因)。

这就是JavaScripts单线程/事件循环设计的妙处~

node.js 的事件驱动

原文:https://www.cnblogs.com/riwang/p/riwang.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!