Search code examples
f#playwright-sharp

How to get Async Values from within Seq.map in F#


With the following code - I am using Microsoft.Playwright to scrape a webpage.

The first line returns System.Collections.Generic.IReadOnlyList

I'm not sure how to get the second line properly as it needs to execute the async over every single line ( it doesn't currently work )

    let! lines = Async.AwaitTask(page.QuerySelectorAllAsync("#statementLines>div"))
    let! values = lines |> Seq.map( fun line -> Async.AwaitTask(line.GetAttributeAsync("data-statementlineid")))

Solution

  • To execute a sequence of async computations and obtain their results, use Async.Sequential or Async.Parallel for sequential or parallel execution respectively.

    Both these methods take a sequence of asyncs as parameter and return their results as an array. Both methods guarantee the order of results in the array to be the same as the order of async computations in the sequence.

    let! lines = Async.AwaitTask(page.QuerySelectorAllAsync("#statementLines>div"))
    let! values = 
      lines 
      |> Seq.map (fun line -> Async.AwaitTask (line.GetAttributesAsync("data-statementlineid")))
      |> Async.Sequential