TypeScript 初心者ですがちょっとハマったので fetch したものを async iterate (async wait) する方法を書いておきます。
まず、具体的な問題はReadableStream<string>
オブジェクトを async wait
で async iterate しようとすると "Type 'ReadableStream' is not an array type or a string type." というエラーが出てしまう、というものです。
なお環境は ts-node v10.9.2 で fetch を使うために以下の設定をしています。
{
"compilerOptions": {
"lib": ["ESNext", "DOM"]
}
}
どうも原因は ReadableStream<string>
が async wait
に必要な [Symbol.asyncIterator]
を実装しているのに TypeScript 側で AsyncIterable<string>
を継承していないことにあるようで、必要だったのは as unknown as AsyncIterable<string>
でした。
export async function fetchStream(url: string, method:string = 'GET'): Promise<AsyncIterable<string>> {
const res = await fetch(url, { method: method } )
if(res.status !== 200 || !res.body) return null
return (res.body.pipeThrough(new TextDecoderStream()) as unknown as AsyncIterable<string>)
}
export async function main() {
const stream = await fetchStream('https://triple-underscore.github.io/rfc-others/RFC2616-ja.html')
if(!stream) return;
for await (const chunk of stream) {
console.log("chunk: " + chunk)
}
}
main();
Comments
Let's comment your feelings that are more than good