当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript async_hooks.createHook函数代码示例

本文整理汇总了TypeScript中async_hooks.createHook函数的典型用法代码示例。如果您正苦于以下问题:TypeScript createHook函数的具体用法?TypeScript createHook怎么用?TypeScript createHook使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了createHook函数的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: collectHandles

// Inspired by https://github.com/mafintosh/why-is-node-running/blob/master/index.js
// Extracted as we want to format the result ourselves
export default function collectHandles(): () => Array<Error> {
  const activeHandles: Map<number, Error> = new Map();

  let hook: AsyncHook;

  try {
    const asyncHooks: typeof import('async_hooks') = require('async_hooks');
    hook = asyncHooks.createHook({
      destroy(asyncId) {
        activeHandles.delete(asyncId);
      },
      init: function initHook(asyncId, type) {
        if (type === 'PROMISE' || type === 'TIMERWRAP') {
          return;
        }
        const error = new ErrorWithStack(type, initHook);

        if (stackIsFromUser(error.stack || '')) {
          activeHandles.set(asyncId, error);
        }
      },
    });

    hook.enable();
  } catch (e) {
    const nodeMajor = Number(process.versions.node.split('.')[0]);
    if (e.code === 'MODULE_NOT_FOUND' && nodeMajor < 8) {
      throw new Error(
        'You can only use --detectOpenHandles on Node 8 and newer.',
      );
    } else {
      throw e;
    }
  }

  return () => {
    hook.disable();

    const result = Array.from(activeHandles.values());
    activeHandles.clear();
    return result;
  };
}
开发者ID:Volune,项目名称:jest,代码行数:45,代码来源:collectHandles.ts

示例2: init

    str = constants.defaultCipherList;
}

////////////////////////////////////////////////////
/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html
////////////////////////////////////////////////////
{
    const hooks: async_hooks.HookCallbacks = {
        init() {},
        before() {},
        after() {},
        destroy() {},
        promiseResolve() {},
    };

    const asyncHook = async_hooks.createHook(hooks);

    asyncHook.enable().disable().enable();

    const tId: number = async_hooks.triggerAsyncId();
    const eId: number = async_hooks.executionAsyncId();

    class TestResource extends async_hooks.AsyncResource {
        constructor() {
            super('TEST_RESOURCE');
        }
    }

    class AnotherTestResource extends async_hooks.AsyncResource {
        constructor() {
            super('TEST_RESOURCE', 42);
开发者ID:Lavoaster,项目名称:DefinitelyTyped,代码行数:31,代码来源:node-tests.ts

示例3: initAsyncHook

  /**
   * 初始化async_hooks
   */
  initAsyncHook() {
    log('init async hooks');
    const self = this;
    const {rootMap, statckFrameMap} = this;

    //@ts-ignore
    const cleanUpContextNode = (id: AsyncId, type: string) => {
      if (!self.statckFrameMap.has(id)) {
        // (process as any)._rawDebug(`no id ${id}`);
        return;
      }

      // (process as any)._rawDebug(`${type}: ${id}`);
      //获取当前销毁asyncId对应的rootId
      const rootId = statckFrameMap.get(id);

      //销毁当前的栈数据
      statckFrameMap.delete(id);

      //判断当前的stackFrameMap还有对于rootId的引用
      let existsRootRef = false;
      //@ts-ignore
      for (let [_, v] of self.statckFrameMap) {
        if (v === rootId) {
          existsRootRef = true;
          break;
        }
      }
      //如果不存在rootId的引用,销毁rootMap的引用
      if (!existsRootRef) {
        rootMap.delete(rootId);
      }

      // (process as any)._rawDebug(statckFrameMap);
      // (process as any)._rawDebug(rootMap);
    };

    async_hooks
      .createHook({
        //@ts-ignore
        init(asyncId, type, triggerAsyncId, resource) {
          // (process as any)._rawDebug(Array.from(arguments).join('|>'));

          //如果当前的triggerAsyncId是rootContext,直接将rootAsyncId关联起来,这样可以省点内存(避免对象的拷贝复制)
          //如果当前的triggerAsyncId是stackContext,将父的rootAsyncId关联起来
          if (rootMap.has(triggerAsyncId)) {
            statckFrameMap.set(asyncId, triggerAsyncId);
          } else {
            if (statckFrameMap.has(triggerAsyncId)) {
              statckFrameMap.set(asyncId, statckFrameMap.get(triggerAsyncId));
            }
          }
        },

        destroy(id) {
          cleanUpContextNode(id, 'destroy');
        },

        promiseResolve(id) {
          cleanUpContextNode(id, 'resolve');
        },

        after(id) {
          cleanUpContextNode(id, 'after');
        },
      })
      .enable();
  }
开发者ID:hufeng,项目名称:node-jsonrpc-dubbo,代码行数:71,代码来源:index.ts

示例4: function

import * as Koa from 'koa'
import * as async_hooks from 'async_hooks'
import * as tracer from 'tracer'

const logger = tracer.console({
  transport: function (data) {
    const asyncId = async_hooks.executionAsyncId()
    console.log(asyncId, data.output)
  }
})

async_hooks.createHook({}).enable()

const app = new Koa()

app.use(async (ctx, next) => {
  logger.log(1)
  await d1()
  ctx.body = {msg: 'hello world'}
  return
})

async function d1 () {
  logger.log(2)
  await d2()
}

async function d2 () {
  logger.log(3)
  // 使用 bluebird.delay 会导致 asyncId 错乱
  // await bluebird.delay(Math.random() * 50)
开发者ID:myfjdthink,项目名称:CodeNode,代码行数:31,代码来源:App.ts


注:本文中的async_hooks.createHook函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。