Situation
I have a function with an asynchronous callback structure, like so:
let readFile: (path: string, callback: (line: string, eof: boolean) => void) => void
However, I would much rather use a function that follows the AsyncIterable/AsyncGenerator pattern:
let readFileV2: (path: string) => AsyncIterable<string>
Issue
Without readFileV2
, I'm stuck reading a file in this cumbersome manner:
let file = await new Promise((res, err) => {
let file = ''
readFile('./myfile.txt', (line, eof) => {
if (eof) { return res(file) }
file += line + '\n'
})
})
.. whereas with readFileV2
, I can elegantly achieve the same result like so:
let file = '';
for await (let line of readFileV2('./myfile.txt')) {
file += line + '\n'
}
Inquiry
Is there a way for me to transform readFile
into readFileV2
?
Updated for clarity:
Is there a method that can be applied universally to convert a function with an async callback into an AsyncGenerator/AsyncIterable format?
If so, could this method be demonstrated using the readFile
function mentioned above?
References
I have come across a couple of related questions:
- How to convert Node.js async streaming callback into an async generator?
- How to convert callback-based async function to async generator
However, none of these seem to offer a definitive solution.