Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何使用 async_hooks 計算每個 async function 花費時間? #29

Open
s1hon opened this issue Nov 8, 2017 · 0 comments
Open

Comments

@s1hon
Copy link

s1hon commented Nov 8, 2017

不知道這邊有沒有了解 async_hooks 的大大....
最近遇到了一些問題想要來這邊請教一下

以下是我的程式碼:

const async_hooks = require('async_hooks')
const fs = require('fs')
const util = require('util')

let indent = 0

function debug(...args) {
  fs.writeSync(1, `${util.format(...args)}\n`)
}

function getIndent(n) {
  return ' '.repeat(n);
}

class MyAsyncCallbacks {
  init(asyncId, type, triggerAsyncId, resource) {
    this[asyncId] = Date.now()
    debug(`${getIndent(indent)}INIT:   ${asyncId} by ${triggerAsyncId}, ${type}, ${resource}`)
  }
  destroy(asyncId) {
    debug(`${getIndent(indent)}DESTRO: ${asyncId}`)
  }
  before(asyncId) {
    debug(`${getIndent(indent)}BEFORE: ${asyncId}`)
    indent += 2
  }
  after(asyncId) {
    indent -= 2
    debug(`${getIndent(indent)}AFTER:  ${asyncId} (${Date.now() - this[asyncId]})`)
  }
  promiseResolve(asyncId) {
    debug(`${getIndent(indent)}PROMIS: ${asyncId} (${Date.now() - this[asyncId]})`)
  }
}
const hook = async_hooks.createHook(new MyAsyncCallbacks()).enable()

fs.writeSync(1, `${getIndent(indent)}>>> Start.....\n`)
setTimeout(() => {
  fs.writeSync(1, `${getIndent(indent)}>>> I'm the setTimeout!\n`)
  new Promise((resolve) => resolve('RESOLVE RETURN')).then((a) => {
    fs.writeSync(1, `${getIndent(indent)}RETURN: ${a}\n`)
  })
}, 3000)
fs.writeSync(1, `${getIndent(indent)}>>> End.....\n`)

我目前是用 this[asyncId] = Date.now() 去存每個 hook 的時間
但是這種方式好像有點髒.....有人有更好的想法嗎?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant