Skip to content

[Feature Request] yield values as soon as they are available #6

Description

@johndeighan

I'm using Windows 11, deno and the civet language
(I'm confident that you'll understand the civet code, similar to CoffeeScript).
Here is my implementation of a function named allPromiseResults() that uses your library:

import {newQueue} from '@henrygd/queue'
import {delay} from "@std/async/delay"

# ---------------------------------------------------------------------------

export mockPromise := <T=unknown>(
		value: T
		ms: number = 10
		): Promise<T> =>

	return new Promise<T> (resolve, reject) =>
		await delay(ms)
		resolve(value)

# ---------------------------------------------------------------------------
# ASYNC

type TThunk<T> = () => Promise<T>
type TSettleResult<T> = [true, T, number] | [false, unknown, number]

export allPromiseResults := <T>(
		lThunks: TThunk<T>[]
		limit: number = 10
		): AsyncGenerator<TSettleResult<T>> ->

	queue := newQueue(limit)
	for thunk,i of lThunks
		try
			response := await queue.add(thunk)
			yield [true, response, i]
		catch err
			yield [false, 'ERROR', i]
	await queue.done()
	return

# ---------------------------------------------------------------------------

lThunks := [
	() => mockPromise('a', 10)
	() => mockPromise('b', 100)
	() => mockPromise('c', 50)
	() => mockPromise('d', 1000)
	() => mockPromise('e', 99)
	() => mockPromise('f', 333)
	() => mockPromise('g', 77)
	() => mockPromise('h', 444)
	() => mockPromise('i', 55)
	() => mockPromise('j', 888)
	() => mockPromise('k', 44)
	() => mockPromise('l', 222)
	]

for await result of allPromiseResults lThunks, 99
	[ok, value, i] := result
	console.log value

At the end you can see how clean the code is that uses this function, which yields the results. In this example, none of the promises reject, but in my real code I handle that.

The problem is that I want to get a yielded value as soon as the corresponding promise resolves or rejects, but the only way I know to yield the values is to utilize the return value from queue.add, but since it's awaited, this just results in getting the values in the order that they appear in the array of promise-returning functions instead of as soon as they resolve/reject.

In this example, I would expect to get 'a', then 'k', then 'c', etc.

Is there a way to achieve this using your library?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions