new AsyncResource(type[, options])


  • type <string> 异步事件的类型。
  • options <Object>
    • triggerAsyncId <number> 创建此异步事件的执行上下文的 ID。默认值: executionAsyncId()
    • requireManualDestroy <boolean> 如果设置为 true,在对象被垃圾回收时将禁用 emitDestroy。通常不需要设置此项(即使手动调用了 emitDestroy),除非检索了资源的 asyncId 并使用它调用了敏感 API 的 emitDestroy。当设置为 false 时,垃圾回收时的 emitDestroy 调用只有在至少有一个活动的 destroy 钩子时才会发生。默认值: false

用法示例:

🌐 Example usage:

class DBQuery extends AsyncResource {
  constructor(db) {
    super('DBQuery');
    this.db = db;
  }

  getInfo(query, callback) {
    this.db.get(query, (err, data) => {
      this.runInAsyncScope(callback, null, err, data);
    });
  }

  close() {
    this.db = null;
    this.emitDestroy();
  }
}