1'use strict';
2// Test that async ids that are added to the destroy queue while running a
3// `destroy` callback are handled correctly.
4
5const common = require('../common');
6const assert = require('assert');
7const async_hooks = require('async_hooks');
8
9const initCalls = new Set();
10let destroyResCallCount = 0;
11let res2;
12
13async_hooks.createHook({
14  init: common.mustCallAtLeast((id, provider) => {
15    if (provider === 'foobar')
16      initCalls.add(id);
17  }, 2),
18  destroy: common.mustCallAtLeast((id) => {
19    if (!initCalls.has(id)) return;
20
21    switch (destroyResCallCount++) {
22      case 0:
23        // Trigger the second `destroy` call.
24        res2.emitDestroy();
25        break;
26      case 2:
27        assert.fail('More than 2 destroy() invocations');
28        break;
29    }
30  }, 2)
31}).enable();
32
33const res1 = new async_hooks.AsyncResource('foobar');
34res2 = new async_hooks.AsyncResource('foobar');
35res1.emitDestroy();
36
37process.on('exit', () => assert.strictEqual(destroyResCallCount, 2));
38