Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/reader.ts>toAsyncIterable

A JavaScript extension package for building strong and modern applications.
Latest
function toAsyncIterable
Re-export
import { toAsyncIterable } from "https://deno.land/x/ayonli_jsext@v0.9.72/reader.ts";

Wraps a source as an AsyncIterable object that can be used in the for await...of... loop for reading streaming data.

Parameters

iterable: AsyncIterable<T> | Iterable<T>

Returns

AsyncIterable<T>

Examples

Example 1

import { toAsyncIterable } from "@ayonli/jsext/reader";

const res = new Response("Hello, World!");

for await (const chunk of toAsyncIterable(res.body!)) {
    console.log("receive chunk:", chunk);
}

Returns

AsyncIterable<T>

Examples

Example 1

import { toAsyncIterable } from "@ayonli/jsext/reader";

// listen to the `onmessage`
const sse = new EventSource("/sse/message");

for await (const msg of toAsyncIterable(sse)) {
    console.log("receive message:", msg);
}

// listen to a specific event
const channel = new EventSource("/sse/broadcast");

for await (const msg of toAsyncIterable(channel, { event: "broadcast" })) {
    console.log("receive message:", msg);
}

Parameters

optional
options: { event?: string; }

Returns

AsyncIterable<string>

Examples

Example 1

import { toAsyncIterable } from "@ayonli/jsext/reader";

const ws = new WebSocket("/ws");

for await (const msg of toAsyncIterable(ws)) {
    if (typeof data === "string") {
        console.log("receive text message:", data);
    } else {
        console.log("receive binary data:", data);
    }
}

Type Parameters

T extends Uint8Array | string

Returns

AsyncIterable<T>

Examples

Example 1

import { toAsyncIterable } from "@ayonli/jsext/reader";

for await (const msg of toAsyncIterable(self)) {
    console.log("receive message from the parent window:", msg);
}

Parameters

target: EventTarget
optional
eventMap: { message?: string; error?: string; close?: string; }

Returns

AsyncIterable<T>

Examples

Example 1

import { toAsyncIterable } from "@ayonli/jsext/reader";

for await (const msg of toAsyncIterable(process)) {
    console.log("receive message from the parent process:", msg);
}

Parameters

target: NodeJS.EventEmitter
optional
eventMap: { data?: string; error?: string; close?: string; }

Returns

AsyncIterable<T>