async_hooks.createHook(callbacks)
-
¥
callbacks
<Object> The Hook Callbacks to register-
init
<Function>init
回调。¥
init
<Function> Theinit
callback. -
before
<Function>before
回调。¥
before
<Function> Thebefore
callback. -
after
<Function>after
回调。¥
after
<Function> Theafter
callback. -
destroy
<Function>destroy
回调。¥
destroy
<Function> Thedestroy
callback. -
promiseResolve
<Function>promiseResolve
回调。¥
promiseResolve
<Function> ThepromiseResolve
callback.
-
-
返回:<AsyncHook> 用于禁用和启用钩子的实例
¥Returns: <AsyncHook> Instance used for disabling and enabling hooks
为每个异步操作的不同生命周期事件注册要调用的函数。
¥Registers functions to be called for different lifetime events of each async operation.
回调 init()
/before()
/after()
/destroy()
在资源的生命周期内为相应的异步事件调用。
¥The callbacks init()
/before()
/after()
/destroy()
are called for the
respective asynchronous event during a resource's lifetime.
所有回调都是可选的。比如,如果只需要跟踪资源清理,则只需要传入 destroy
回调。可以传递给 callbacks
的所有函数的细节在 钩子回调 部分。
¥All callbacks are optional. For example, if only resource cleanup needs to
be tracked, then only the destroy
callback needs to be passed. The
specifics of all functions that can be passed to callbacks
is in the
Hook Callbacks section.
import { createHook } from 'node:async_hooks';
const asyncHook = createHook({
init(asyncId, type, triggerAsyncId, resource) { },
destroy(asyncId) { }
});
const async_hooks = require('node:async_hooks');
const asyncHook = async_hooks.createHook({
init(asyncId, type, triggerAsyncId, resource) { },
destroy(asyncId) { }
});
回调将通过原型链继承:
¥The callbacks will be inherited via the prototype chain:
class MyAsyncCallbacks {
init(asyncId, type, triggerAsyncId, resource) { }
destroy(asyncId) {}
}
class MyAddedCallbacks extends MyAsyncCallbacks {
before(asyncId) { }
after(asyncId) { }
}
const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
因为 promises 是异步资源,其生命周期通过异步钩子机制进行跟踪,所以 init()
、before()
、after()
和 destroy()
回调不能是返回 promises 的异步函数。
¥Because promises are asynchronous resources whose lifecycle is tracked
via the async hooks mechanism, the init()
, before()
, after()
, and
destroy()
callbacks must not be async functions that return promises.