Skip to content

Question: get the first success from Async<Result<'ok, 'error>> list? #340

Open

Description

@njlr

Like List.sequenceAsyncResultM but would stop at the first success.

Is there something like this already provided?

let firstSuccess (tasks : Async<Result<'ok, 'error>> list) : Async<Result<'ok, 'error list>> =
  let rec loop (errors : 'e list) tasks =
    async {
      match tasks with
      | [] ->
        return Error (List.rev errors)
      | x :: xs ->
        match! x with
        | Ok t ->
          return Ok t
        | Error error ->
          return! loop (error :: errors) xs
    }

  loop [] tasks

If not, would a PR be accepted?

Thanks!

Activity

  1. TheAngryByrd commented on Sep 24, 2025

    @TheAngryByrd
    Collaborator

    I don't think anything like this is available currently. It feels like a derivative of List.tryPick but accumulates errors. Maybe we should make that available with an additional helper to yield if the list is already a group

    module List =
        module AsyncResult =
            let tryPick f tasks =
                async {
                    let mutable errors = ListCollector()
                    let mutable result = ValueNone
    
    
                    for task in tasks |> List.takeWhile (fun _ -> result.IsNone) do
                        match! f task with
                        | Ok t -> result <- ValueSome(Ok t)
                        | Error error -> errors.Add error
    
                    match result with
                    | ValueSome okResult -> return okResult
                    | ValueNone -> return Error(errors.Close())
                }
    
            let tryYield tasks = tryPick id tasks
    
  2. njlr commented on Sep 29, 2025

    @njlr
    ContributorAuthor

    It feels like a derivative of List.tryPick but accumulates errors.

    Hmmm does this make it part of AsyncValidation then?

  3. TheAngryByrd commented on Sep 29, 2025

    @TheAngryByrd
    Collaborator

    Hmmm does this make it part of AsyncValidation then?

    Yeah probably.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions