钩子回调


promise 生命周期中的关键事件分为四个方面:promise 的创建、调用继续句柄之前/之后或 await 前后,以及当 promise 解决或拒绝时。

虽然这些钩子与 async_hooks 的钩子相似,但它们缺少 destroy 钩子。 其他类型的异步资源通常表示套接字或文件描述符,它们具有不同的“关闭”状态来表达 destroy 生命周期事件,而只要代码仍然可以访问它们,则 promise 就仍然可用。 垃圾收集跟踪用于使 promise 适合 async_hooks 事件模型,但是这种跟踪非常昂贵,而且它们甚至不一定会被垃圾收集。

因为 promise 是异步的资源,其生命周期通过 promise 钩子机制进行跟踪,所以 init()before()after()settled() 回调不能是异步的函数,因为它们创建了更多会产生无限循环的 promise。

虽然此 API 用于将 promise 事件提供给 async_hooks,但两者之间的顺序是未定义的。 两个 API 都是多租户的,因此可以以相对于彼此的任何顺序产生事件。

Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or around an await, and when the promise resolves or rejects.

While these hooks are similar to those of async_hooks they lack a destroy hook. Other types of async resources typically represent sockets or file descriptors which have a distinct "closed" state to express the destroy lifecycle event while promises remain usable for as long as code can still reach them. Garbage collection tracking is used to make promises fit into the async_hooks event model, however this tracking is very expensive and they may not necessarily ever even be garbage collected.

Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the init(), before(), after(), and settled() callbacks must not be async functions as they create more promises which would produce an infinite loop.

While this API is used to feed promise events into async_hooks, the ordering between the two is undefined. Both APIs are multi-tenant and therefore could produce events in any order relative to each other.