Last active
October 12, 2016 19:22
-
-
Save trevnorris/083f3e6df3458434ba0fada241a3abe3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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