我正在使用这个库https://www.npmjs.com/package/event-iterator来使用异步迭代器。我有以下功能
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();
};
});
}
我有一个使用它的功能如下
export function subscribeMyServicePromise(): AsyncIterable<TrieProof> {
return grpcClientReadableStreamToAsyncIterator(
<some function which returns grpc.ClientReadableStream>
);
}
当我尝试在这样的异步函数中使用时
(async () => {
console.log("here");
let myAsyncIterableObj: AsyncIterable<MyObj> = await subscribeMyServicePromise()
for await (const tp of myAsyncIterableObj){
console.log("processing: ");
}
console.log("now here");
}()
它只是打印以下内容并退出
here
processing:
processing:
processing:
processing:
我的问题是为什么不打印“现在在这里”。看起来进程在 for await 循环结束后结束。我怎样才能避免这种情况?
编辑
我可以这样做
const iterator = myAsyncIterableObj[Symbol.asyncIterator]()
await iterator.next();
await iterator.next();
await iterator.next();
await iterator.next();
console.log("now here")
它工作正常。我的写作方式有问题for-await
吗?