Created
September 28, 2023 19:13
-
-
Save bnoordhuis/e411566adb3143995487858cf254a2c2 to your computer and use it in GitHub Desktop.
[node.js] count active promises via the V8 inspector
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
"use strict" | |
const inspector = require("node:inspector/promises") | |
const session = new inspector.Session() | |
session.connect() | |
countPromises(session).then(console.log) | |
async function countPromises(session) { | |
// resource management: put all results in an object group | |
const objectGroup = crypto.randomUUID() | |
// get reference to global Promise object prototype | |
const {result:{objectId:promisePrototypeOID}} = await session.post( | |
"Runtime.evaluate", | |
{objectGroup, expression:"Promise.prototype"}) | |
// get reference to array holding all promises | |
const {objects:{objectId:promisesArrayOID}} = await session.post( | |
"Runtime.queryObjects", | |
{objectGroup, prototypeObjectId:promisePrototypeOID}) | |
// get contents of array; disable preview for performance reasons | |
const {result} = await session.post( | |
"Runtime.getProperties", | |
{objectId:promisesArrayOID, ownProperties:true, generatePreview:false}) | |
// free resources, don't wait for completion | |
session.post("Runtime.releaseObjectGroup", {objectGroup}) | |
// array includes "length" property, subtract one to correct | |
return result.length - 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment