I am using this library https://www.npmjs.com/package/event-iterator to use async iterators. I have the following function
export function grpcClientReadableStreamToAsyncIterator<T>(
stream: grpc.ClientReadableStream<T>
): AsyncIterable<T> {
return new EventIterator((queue) => {
stream.addListener("data", queue.push);
stream.addListener("close", queue.stop);
stream.addListener("error", queue.fail);
return () => {
stream.removeListener("data", queue.push);
stream.removeListener("close", queue.stop);
stream.removeListener("error", queue.fail);
stream.destroy();
};
});
}
I have a function which uses it as follows
export function subscribeMyServicePromise(): AsyncIterable<TrieProof> {
return grpcClientReadableStreamToAsyncIterator(
<some function which returns grpc.ClientReadableStream>
);
}
When I try to use in an async function like this
(async () => {
console.log("here");
let myAsyncIterableObj: AsyncIterable<MyObj> = await subscribeMyServicePromise()
for await (const tp of myAsyncIterableObj){
console.log("processing: ");
}
console.log("now here");
}()
It just prints the following and exits
here
processing:
processing:
processing:
processing:
My question is why is not printing "now here". Looks like the process ends after the for await loop ends. How can I avoid this?
EDIT
I could do this
const iterator = myAsyncIterableObj[Symbol.asyncIterator]()
await iterator.next();
await iterator.next();
await iterator.next();
await iterator.next();
console.log("now here")
and it works fine. Is there any problem with my way of writing for-await
?