Skip to content

async generators: for await ... of !this #192

@malcolmstill

Description

@malcolmstill

Does it make sense in an async function* (async generator) to for await (const _ of <x>) where x is something other than this?

What I'm playing around with is turning a websocket connection into an async generator as per https://www.bignerdranch.com/blog/asyncing-feeling-about-javascript-generators/

Then doing:

export async function* WebSocketStream({ socket }) {
  let messages = []

  yield <p>Awaiting data</p>

  for await (const msg of socket) {
    messages.push(msg)
    yield (
      <div>
        {messages.map((m, i) => (
          <div key={i}>{m}</div>
        ))}
      </div>
    )
  }
}

where socket is a websocket (from new WebSocket(addr))

Right enough this works, and I get a stream of messages. But I have some unexpected behaviour where I see certain changes only when data comes across the websocket. This leads me to think that the issues are because I am no longer awaiting on this.

  1. Does it make sense to not for await this?
  2. Is there some other way I should be doing this? Intuitively I want to for await the combination (i.e. a multiplex) of this and socket, but I'm not sure how to do that (funnily enough I came across this answer of yours @brainkim: https://stackoverflow.com/a/58809794 whilst googling)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions