Take this example function
async function foo () {
const res = await fetchData()
const out = await processData(res)
return out
}
Imagine that I notice fetchData
is slow and I want to quickly profile with a generic timer function / generator:
async function foo () {
for (let time of timer()) {
const res = await fetchData()
}
const out = await processData(res) // error res is undefined
return out
}
This now breaks the code as res
is no longer defined. I could define let res
before the block, or use var
but that means modifying source code for some temporary profiling code. I guess this is the very point of const
is scoping to statements. However, I still feel there is a way of maintaining scope and triggering an event before and after a set of lines?
I am not married to generators. Closures could do the same job but have the same scoping issue. Other syntax suggestions welcome.
How can I wrap some arbitrary block of code but maintain the variable scope? Maybe with a proxy? Something similar to context managers from python. This could be on the edge of the limitations of the language?