11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst assert = require('assert');
51cb0ef41Sopenharmony_ciconst async_hooks = require('async_hooks');
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciconst id_obj = {};
81cb0ef41Sopenharmony_cilet collect = true;
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ciconst hook = async_hooks.createHook({
111cb0ef41Sopenharmony_ci  before(id) { if (collect) id_obj[id] = true; },
121cb0ef41Sopenharmony_ci  after(id) { delete id_obj[id]; },
131cb0ef41Sopenharmony_ci}).enable();
141cb0ef41Sopenharmony_ci
151cb0ef41Sopenharmony_ciprocess.once('uncaughtException', common.mustCall((er) => {
161cb0ef41Sopenharmony_ci  assert.strictEqual(er.message, 'bye');
171cb0ef41Sopenharmony_ci  collect = false;
181cb0ef41Sopenharmony_ci}));
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_cisetImmediate(common.mustCall(() => {
211cb0ef41Sopenharmony_ci  process.nextTick(common.mustCall(() => {
221cb0ef41Sopenharmony_ci    assert.strictEqual(Object.keys(id_obj).length, 0);
231cb0ef41Sopenharmony_ci    hook.disable();
241cb0ef41Sopenharmony_ci  }));
251cb0ef41Sopenharmony_ci
261cb0ef41Sopenharmony_ci  // Create a stack of async ids that will need to be emitted in the case of
271cb0ef41Sopenharmony_ci  // an uncaught exception.
281cb0ef41Sopenharmony_ci  const ar1 = new async_hooks.AsyncResource('Mine');
291cb0ef41Sopenharmony_ci  ar1.runInAsyncScope(() => {
301cb0ef41Sopenharmony_ci    const ar2 = new async_hooks.AsyncResource('Mine');
311cb0ef41Sopenharmony_ci    ar2.runInAsyncScope(() => {
321cb0ef41Sopenharmony_ci      throw new Error('bye');
331cb0ef41Sopenharmony_ci    });
341cb0ef41Sopenharmony_ci  });
351cb0ef41Sopenharmony_ci
361cb0ef41Sopenharmony_ci  // TODO(trevnorris): This test shows that the after() hooks are always called
371cb0ef41Sopenharmony_ci  // correctly, but it doesn't solve where the emitDestroy() is missed because
381cb0ef41Sopenharmony_ci  // of the uncaught exception. Simple solution is to always call emitDestroy()
391cb0ef41Sopenharmony_ci  // before the emitAfter(), but how to codify this?
401cb0ef41Sopenharmony_ci}));
41