Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// This has been updated. You'll have to go back in time in the gist history to
// see older versions.
const { writeSync } = require("fs")
const async_hooks = require("async_hooks")
async function printLeakedEvents(f) {
// Track all active event IDs
const eventIDs = new Set()
// Set up an async hook to increment and decrement the counter
const asyncHook = async_hooks.createHook({
init: (asyncID) => {
eventIDs.add(asyncID)
},
after: (asyncID) => {
eventIDs.delete(asyncID)
},
});
// run the function with the async hook enabled
asyncHook.enable()
try {
await f()
} finally {
asyncHook.disable()
}
// print the number of hooks (using writeSync to be 100% sure that we don't
// create any new events)
writeSync(1, eventIDs.size + "\n")
}
async function main() {
// do no async stuff
await printLeakedEvents(async () => 0)
// do no async stuff again to make sure it's reliable
await printLeakedEvents(async () => 0)
// leak a promise
await printLeakedEvents(async () => {
// unresolved promise
new Promise(function(resolve, reject) { setTimeout(resolve, 1000); })
})
// create a promise and resolve it correctly, including `then` and `await`
await printLeakedEvents(async () => {
// unresolved promise
await new Promise(function(resolve, reject) {
setTimeout(resolve, 1000);
}).then(() => {
// do nothing, but we do want a "then"
})
})
}
main()
// Output:
// 6
// 6
// 8
// 8
// The questions:
//
// 1. Why are 6 events created ("init"ed) but not resolved when I call a
// synchronous function?
//
// 2. Why do I see a net event change of 8 regardless of whether I correctly
// `await` the promise with a `then`, vs. simply leaking it?
@garybernhardt

This comment has been minimized.

Copy link
Owner Author

@garybernhardt garybernhardt commented Mar 6, 2019

a more complete version from @wolever that seems to actually work: https://gist.github.com/wolever/d95c7143af5789161868c97a0ce9e2fe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment