node/test/parallel/test-async-hooks-recursive-stack-runInAsyncScope.js
Ali Ijaz Sheikh 523a1550a3 async_hooks: deprecate unsafe emit{Before,After}
The emit{Before,After} APIs in AsyncResource are problematic.

* emit{Before,After} are named to suggest that the only thing they do
  is emit the before and after hooks. However, they in fact, mutate
  the current execution context.
* They must be properly nested. Failure to do so by user code leads
  to catastrophic (unrecoverable) exceptions. It is very easy for the
  users to forget that they must be using a try/finally block around
  the code that must be surrounded by these operations. Even the
  example provided in the official docs makes this mistake. Failing
  to use a finally can lead to a catastrophic crash if the callback
  ends up throwing.

This change provides a safer `runInAsyncScope` API as an alternative
and deprecates emit{Before,After}.

PR-URL: https://github.com/nodejs/node/pull/18513
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Andreas Madsen <amwebdk@gmail.com>
2018-02-09 13:03:34 -08:00

21 lines
636 B
JavaScript

'use strict';
require('../common');
const assert = require('assert');
const async_hooks = require('async_hooks');
// This test verifies that the async ID stack can grow indefinitely.
function recurse(n) {
const a = new async_hooks.AsyncResource('foobar');
a.runInAsyncScope(() => {
assert.strictEqual(a.asyncId(), async_hooks.executionAsyncId());
assert.strictEqual(a.triggerAsyncId(), async_hooks.triggerAsyncId());
if (n >= 0)
recurse(n - 1);
assert.strictEqual(a.asyncId(), async_hooks.executionAsyncId());
assert.strictEqual(a.triggerAsyncId(), async_hooks.triggerAsyncId());
});
}
recurse(1000);