Skip to content

Instantly share code, notes, and snippets.

@Swizec
Created November 3, 2021 15:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swizec/30df527907e3488a546075b3ec691dd9 to your computer and use it in GitHub Desktop.
Save Swizec/30df527907e3488a546075b3ec691dd9 to your computer and use it in GitHub Desktop.
An attempt to detect long running promises in JavaScript code on the server. Unfortunately it can't get a reference to execution context, which diminishes its usefulness
const ah = require('async_hooks')
const promiseTimes = {}
// if a promise runs for more than 10s, something's wrong
const MAX_TIME = 10 * 1000
ah.createHook({
// save meta data when async instantiates
init(asyncId, type) {
promiseTimes[asyncId] = {
type
}
},
// save timestamp when promise begins
before(asyncId) {
if (!promiseTimes[asyncId]) {
promiseTimes[asyncId] = {}
}
promiseTimes[asyncId].time = new Date()
// warn if a promise doesn't resolve in time
promiseTimes[asyncId].timer = setTimeout(() => {
if (promiseTimes[asyncId]) {
Logger.warn(`Promise not resolved within ${MAX_TIME}ms`, {
type: promiseTimes[asyncId].type
})
}
}, MAX_TIME)
},
// check duration and cleanup when promise ends
after(asyncId) {
if (promiseTimes[asyncId]) {
const delta = new Date() - promiseTimes[asyncId].time
if (delta > MAX_TIME) {
Logger.warn(`Promise ran longer than ${MAX_TIME}ms`, {
delta,
type: promiseTimes[asyncId].type
})
}
}
},
// cleanup
destroy(asyncId) {
if (promiseTimes[asyncId]) {
clearTimeout(promiseTimes[asyncId].timer)
delete promiseTimes[asyncId]
}
}
}).enable()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment