首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将回调注册到nodejs中的特定阶段

如何将回调注册到nodejs中的特定阶段
EN

Stack Overflow用户
提问于 2020-03-06 07:43:45
回答 1查看 82关注 0票数 0

跟踪事件循环上的医生,

考虑下面的片段,

代码语言:javascript
复制
const fs = require('fs');
const http = require('http');

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

http.createServer(function (req, res) {
  res.write('Hello World!');
  console.log("Response sent");
  res.end();
}).listen(8081);

setInterval(() => console.log("Timeout callback"), 1000)

现在,由于nodejs是事件驱动的,所以我假设nodejs下的内容将触发特定于节点的事件。

问题1:我的假设正确吗?

现在,当有一个传入的HTTP请求到nodejs时,函数代码和相关变量驻留在eventloop循环之外。这意味着应该有数据结构来弥补这一差距。

问题2:nodejs中遇到的事件如何在特定阶段执行回调函数?

EN

回答 1

Stack Overflow用户

发布于 2020-03-06 08:06:54

也许,我理解偶数循环工作原理的方法与您不同,但我展示了基于您的代码的理解(为了便于解释,我添加了一些更同步的代码行)。

代码语言:javascript
复制
const fs = require('fs');
const http = require('http');

// Every time Nodejs faces a block of synchronous code, it will push this function into a call-stack (the execution stack like other programming language)
console.log('run 1');

// Everty time NodeJS faces a block of asynchronous code, it will pass its jobs and its callback function to a lib called libuv to handle.
// when libuv finishs its job (asynchronous operation), it will push the callback function into a queue called event-queue
fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Another synchronous code
console.log('run 2');

// Another asynchronous code
http.createServer(function (req, res) {
  res.write('Hello World!');
  console.log("Response sent");
  res.end();
}).listen(8081);

在所有这些注释之后,您可以想象我们有一个堆栈和一个队列。事件循环的重复工作是

步骤1:查看堆栈(调用堆栈),如果里面有函数,执行它直到堆栈为空。

步骤2:查看队列(事件队列),如果里面有任何函数,执行它直到队列为空。

步骤3:重复步骤1。

P/S:为了获得更多的细节和可视化,这个视频是描述事件循环工作方式的最好来源。希望能帮上忙

链接

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60559584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档