fable-compiler / fable-promise

Fable bindings for JS promise
http://fable.io/fable-promise/
MIT License
19 stars 7 forks source link

suggestion: AsyncIterable.iterAsync/iterPromise function #56

Open joprice opened 2 months ago

joprice commented 2 months ago

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: https://github.com/fable-compiler/fable-promise/blob/b40f8cd1d6b3582baea1aeaf98b180e3d27bc4f0/src/AsyncIterable.fs#L49.

MangelMaxime commented 2 months ago

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?

joprice commented 2 months ago

I don't think the promise will necessarily be returned by fable if the function's return type isn't JS.Promise: https://fable.io/repl/#?code=PYBwpgdgBAYghgIwDZgHQGFgCcwChSRQBSAzgJIQAuYWouulAnuFOnBAMZhJJyUCWwCABVgAa0gAKAJRQAvFA68SJKJAAm9FJSj9qWKJLgcBQgFyt2XHn0EjxhALQA+KAHJhUF1ACuEPbKSejSIKBZEAMqoAIIkjJxk+qFgADweztLhUQAKtAC2-CSpfnqucrhQlVDaUJQO0ApsnNy8pvYSEDIVVWAFlKQAogAeIAYyUABEU0ZxnIaycq4A3t2VAGbYUHAA7nB6hhxCJDoAbnBIPmBQwGu6SchgsitVL7VYjFDPr987ezrGbUkdQ6ABooGcLo9Vq8AL6KPgcAAWhhoWCe0O+lX4t0kqN0EGOVjAN1q9VQhwJlCwPhM2HRmIZUAQODgYgA3BjMTDOd9KIjaNtcVg0RyGdyXtyYdIZFMJlowDpglgAEyGAF2CxNaytOyiDpeVweA3EHL5QrFfyUDKGJXJLIxWYcRIhB5pYQZe25YAFIopEpW+TQmrAwiNIk2Np6qTSaG9PSDEZjWSymbxDjzeTLaEbAy-faSCnHcHnS7XW62h70zFUj5fRlbXb7dVCIH1MEQy4xsXwyhIlHCqv17H9gz8SlEkkhiDko5Uml1NGfHmM5lgVmi+tQcWbvkCoUi5fbyqS6XSWX0JWGNZ+KAAfSgQ2NXp9aBIKDAICgAEYAAx-qAAD6uPwADmEDYI8gHAWBEG4EqqqSNe0D3o+3jPuaqBvmAH7fn+P5QLIQG6DBOBAA&html=Q&css=Q