Skip to content
Go back

How Async Generators Work with SSE in JavaScript

Published:  at  07:35 AM

Async generators in JavaScript provide an elegant way to handle Server-Sent Events (SSE)โ€”especially when dealing with token-by-token or chunked data streams from LLMs.

Letโ€™s explore how they help you handle real-time streaming with ease.


๐ŸŽฅ What is SSE?

SSE (Server-Sent Events) lets the server push text messages to the browser over a single HTTP connection. Each message looks like:

data: Hello

data: world!

SSE is great for:


๐Ÿ”„ Enter Async Generators

An async function* lets you:


โœจ Example: Consuming SSE with Async Generator

async function* parseSSE(stream) {
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    const lines = buffer.split('\n');
    buffer = lines.pop();

    for (const line of lines) {
      if (line.startsWith('data: ')) {
        yield line.slice(6);
      }
    }
  }
}

Usage:

const response = await fetch('/api/stream', {
  method: 'POST',
  headers: { Accept: 'text/event-stream' }
});

for await (const chunk of parseSSE(response.body)) {
  console.log('Chunk:', chunk);
}

๐Ÿš€ Benefits


๐Ÿ”š Summary

Async generators give you streaming superpowers with SSE:

Perfect for modern AI-powered apps using LLM APIs that stream!


Suggest Changes

Previous Post
How does generator functions in JavaScript works?
Next Post
EventSource vs Async Generator - What to Use for LLM Streaming?