CAF
CAF copied to clipboard
How can I dynamically detect a CAF-wrapped generator?
Thank you for this amazing library. I love being able to cancel async activity.
- Background: Legacy parts of my codebase use traditional async functions that can't be canceled. Modern parts are using CAF.
- Question: Is there a way I can introspect a CAF-wrapped generator to ensure that it's a CAF-wrapped function?
Example of a legacy and modern function in my codebase:
const syncOrgsModern = CAF(function *syncOrgs(signal) {
yield doTheWork();
});
async function syncOrgsLegacy() {
await doTheWork();
}
As we migrate more code to use CAF, I'd like to be able to dynamically inspect values such as these to ensure they're CAF-wrapped functions and not traditional sync functions. I want to do this so that my code can provide better error messages and more intelligence if something is configured wrong between the legacy way (traditional sync) and the modern way (CAF-wrapped generators).
Thanks again for the time you spend maintaining this library. It's really, really awesome. 🙏
Interesting request... should be pretty easy to add a value to each CAF instance so that they're inspectable.
This line is where that instance function is defined... so inserting there a few lines of code to assign a property to the function before returning it should be enough.
Something sorta like (untested):
function CAF(generatorFn) {
Object.defineProperty(
instance,
"name",
{ value: `CAF:${generatorFn.name || "anonymous"}` }
);
return instance;
// *****************
function instance(tokenOrSignal,...args){
// ..
}
}
Then you could inspect them like this:
var f = CAF(function *myFunc(){ .. });
var g = CAF(function*(){ .. });
f.name; // CAF:myFunc
g.name; // CAF:anonymous
Think that would work?
Very cool, yep. I'll play with making a PR since I like CAF and this seems like a fun thing to contribute.
excellent, thanks! :)
How does this look? https://github.com/getify/CAF/pull/26 I did this for fun more than anything. We use a separate variable to track which pieces of our code use CAF, but it'd be cool if it was built-in. No worries if you think it's unnecessary.