Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

suggestion: AsyncIterable.iterAsync/iterPromise function #56

Open
joprice opened this issue Jul 27, 2024 · 4 comments
Open

suggestion: AsyncIterable.iterAsync/iterPromise function #56

joprice opened this issue Jul 27, 2024 · 4 comments

Comments

@joprice
Copy link

joprice commented Jul 27, 2024

The AsyncIteratable.iter function doesn't allow processing an item using a promise. It would be convenient to have another helper that adds an await here:

action(token, value)
.

@MangelMaxime
Copy link
Member

I am not familiar with the AsyncIterable API so I am not sure for what it is used for.

But would change the code to be enough? I just added await. In theory, it means that if you provide a promise it will be awaited and if you don't provide a promise it will also be awaited because JavaScript will transform the provided function to an async / `promise.

I didn't test the code, and I don't know if JavaScript allows to have an await here, but I don't see why not.

/// Iterates AsyncIterable. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
let iter (action: CancellationToken -> 'T -> unit) (iterable: JS.AsyncIterable<'T>): JS.Promise<unit> =
    let token = CancellationToken()
    emitJsExpr () """(async () => {
    for await (const value of iterable) {
        try {
            await action(token, value)
        } catch (err) {
            if (err instanceof token.constructor) {
                break;
            }
            throw(err);
        }
    }
})()"""

The other solution would probably be to create a let iterAsync function?

@MangelMaxime
Copy link
Member

MangelMaxime commented Oct 20, 2024

I was looking at this issue again and I don't exactly see what your last message was trying to point to.

Could you please try to explain what is missing between iter and iter2.

@joprice
Copy link
Author

joprice commented Oct 20, 2024

At the call site, iter1 creates a promise, but does not return it. You can see that it's wrapped in braces without a return keyword:

(iterable) => iter((_arg, x) => {
    new Promise(resolve => setTimeout(resolve, 1000));
}, iterable);

Whereas in iter2, returned implicitly, since it is fat arrow function with a single expression:

(iterable) => iter2((_arg, x) => (new Promise(resolve => setTimeout(resolve, 1000))), iterable);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants