Skip to content

Instantly share code, notes, and snippets.

@brysgo
Last active March 19, 2024 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brysgo/1ef5d6c210cfc843f173243ff9abc7b3 to your computer and use it in GitHub Desktop.
Save brysgo/1ef5d6c210cfc843f173243ff9abc7b3 to your computer and use it in GitHub Desktop.
verbose logging of nodejs async function by converting to generator
async function myAsyncFunction() {
await callToSomethingAsync();
someNonAsyncFunctionCall();
await callToAnotherAsyncThing();
}
function convertAsyncFunctionToGenerator(fn) {
// Convert the function to string
let stringFn = fn.toString();
// Carefully replace 'async function' with 'function*'
// This pattern looks for 'async function' declarations, considering spaces and avoiding partial matches like 'asyncFunction'
stringFn = stringFn.replace(/async function/g, "function*");
// Replace 'await' with 'yield'
stringFn = stringFn.split("await").join("yield");
try {
// Attempt to eval the transformed string into a function
// Note: This approach has limitations and might not work for all functions, especially those relying on external scope or complex contexts
const genFunc = eval(`(${stringFn})`);
return genFunc;
} catch (e) {
console.error("Conversion failed:", e);
return null;
}
}
async function debugAsyncFunction(asyncFunction) {
const generatorFunction = convertAsyncFunctionToGenerator(asyncFunction);
const iterator = generatorFunction();
let result = iterator.next();
let i = 1;
while (!result.done) {
result = await result.value; // Await the yielded promise
console.log(`> await ${generatorFunction.toString().split("yield")[i].split("\n")[0]}`);
result = iterator.next(result);
i++;
}
}
// Usage
debugAsyncFunction(myAsyncFunction);
// Will console.log
//> await callToSomethingAsync();
//> await callToAnotherAsyncThing();
// Helping you figure out when each of your async things are getting called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment