钩子回调
【Hook callbacks】
承诺生命周期中的关键事件被划分为四个方面:承诺的创建、在调用续处理程序之前/之后或在 await 周围,以及承诺解决或拒绝时。
【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.】
虽然这些钩子类似于 async_hooks 的钩子,但它们缺少 destroy 钩子。其他类型的异步资源通常表示套接字或文件描述符,这些资源有一个明确的“关闭”状态,用来表示 destroy 生命周期事件,而 Promise 只要代码仍然可以访问它们,就可以继续使用。垃圾回收跟踪用于使 Promise 适应 async_hooks 事件模型,然而这种跟踪代价非常高,并且它们可能根本永远不会被垃圾回收。
【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.】
因为 Promise 是异步资源,其生命周期通过 Promise 钩子机制进行跟踪,因此 init()、before()、after() 和 settled() 回调函数不能是异步函数,因为它们会创建更多的 Promise,从而导致无限循环。
【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.】
虽然该 API 用于将 promise 事件传入 async_hooks,但两者之间的顺序是不确定的。这两个 API 都是多租户的,因此相对于彼此可能会产生任意顺序的事件。
【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.】