Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// map will store all the stack traces recorded at init().
var map = new Map();
var async_hooks = require('async_hooks');
async_hooks.createHook({ init }).enable();
function init(id, type, parentId) {
const obj = {};
// Capture the stack trace, omitting the call to init().
Error.captureStackTrace(obj, init);
// Store the stack trace and parentId. The later will be used to retrieve
// the stack from the parent call.
map.set(id, [obj.stack, parentId, async_hooks.currentId()]);
}
var p = new Promise(function f1() {
(function foo() { throw new Error() })();
});
var p2 = (function q1() {
return p.catch(function f2() {
(function bar() { throw new Error() })();
})
})();
p2.catch(genStack);
function genStack() {
var cid = async_hooks.currentId();
var item;
console.log(new Error().stack.substr(6));
do {
item = map.get(cid);
console.log(item[0]);
// Swap item[1] for item[2] to see stack based on currentId()
cid = item[1];
} while (cid > 0);
}
// parentId stack:
// genStack
// bar
// f2
// foo
// f1
// <anonymous>
// currentId stack:
// genStack
// <anonymous>
// But the two can be mixed/matched to get different stacked. e.g.:
// genStack
// bar
// f2
// q1
// <anonymous>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment