为什么console.log在async_hooks Node.js中变得无限

时间:2019-05-31 09:59:37

标签: javascript node.js

为什么init中存在console.log之前,之后,销毁async_hooks中的函数会导致无限最大调用堆栈超出问题?

下面的代码为什么会变成无限,

let asycn_hooks = require('async_hooks');

async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    console.log(asyncId);
  },
  before(asyncId) {
    console.log(asyncId);
  },
  after(asyncId) {
    console.log(asyncId);
  },
  destroy(asyncId) {
    console.log(asyncId);
  },
}).enable();
setTimeout(() => {
  console.log('>>>', async_hooks.executionAsyncId());
}, 10);

但是下面的代码没有

let async_hooks = require('async_hooks');
let fs = require('fs');

async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    fs.writeFileSync(1,`init ${asyncId} \n`);
  },
  before(asyncId) {
    fs.writeFileSync(1,`before ${asyncId} \n`);
  },
  after(asyncId) {
    fs.writeFileSync(1,`after ${asyncId} \n`);
  },
  destroy(asyncId) {
    fs.writeFileSync(1,`destroy ${asyncId} \n`);
  },
}).enable();

setTimeout(() => {
    console.log('>>>', async_hooks.executionAsyncId());
  }, 0);

1 个答案:

答案 0 :(得分:0)

原因console.log是异步according to the docs