-1

我是 Node 的新手,所以我不清楚以下代码行为:

function step(iteration) {
  if (iteration === 10) return;

  process.nextTick(() => {
    step(iteration + 1); // Recursive call from nextTick handler.
    console.log(`nextTick iteration: ${iteration}`);    
  });

  http.request({hostname: '127.0.0.1', port: 5000}, (response) => {
    console.log("here !");
  }).end();

  setImmediate(() => {
    console.log(`setImmediate iteration: ${iteration}`);    
  });
}
step(0);

输出:

nextTick iteration: 0
...
nextTick iteration: 9
setImmediate iteration: 0
...
setImmediate iteration: 9
here !
here !
here !
here !
here !
here !
here !
here !
here !
here !

问题是:

1)为什么http.request()会在之后触发回调setImmediate()?我不明白,为什么setImmediate()通常被称为:它的回调是在循环期间注册的。但正如文档所说,这setImmediate()是一个检查阶段,应该在轮询后在事件循环中处理。如果我理解正确的话,http.request()应该nextTick()是那个轮询阶段;

2)但是如果在pollhttp.request()中没有处理,它会在哪个阶段发生?特别是考虑到它在.setImmediate()

我的 Node.js 版本是 6.11.2。提前感谢您的解释。

4

1 回答 1

-1

要回答您的问题:

  1. http.request() 之前被调用setImmediate()。但是,http.request是异步的。在您的情况下,直到请求解决后才会运行回调。这意味着虽然它首先被调用,但回调直到稍后的时间点才记录任何内容——并且该时间点是在setImmediate()解决之后。
  2. 即使setImmediate将其回调按照排队的顺序排队执行,它们仍然能够在请求返回之前解决。

为了按顺序处理您的步骤,请考虑将 to 的内容移动nextTick到请求的回调中:

function step(iteration) {
  if (iteration === 10) return;

  http.request({hostname: '127.0.0.1', port: 8000}, (response) => {
    console.log("here !");

    step(iteration + 1); // Recursive call from nextTick handler.

    console.log(`nextTick iteration: ${iteration}`);    
  }).end();

  setImmediate(() => {
    console.log(`setImmediate iteration: ${iteration}`);    
  });
}
step(0);

在该代码段中,我删除了nextTick,但如果需要,您可以安全地将其添加到回调中。

于 2017-08-24T22:29:17.613 回答