0

I have a function that I want to run 5 at a time from a chunked list and then wait a second so as not to hit an Api rate limit. I know the code is wrong but it is as far as I have got.

 let ordersChunked = mOrders |> List.chunkBySize 5
 for fiveOrders in ordersChunked do
 let! tasks = 
 fiveOrders 
 |> List.map (fun (order) -> trackAndShip(order) )
 |> Async.Parallel
 Async.Sleep(1000) |> ignore

trackAndShip is an async function not a task and I get a little confused about the two.

Some of the answers I have read add |> Async.RunSynchronously to the end of it - and I do that at the top level but I don't feel it is good practice here ( and I would need to convert async to Task? )

This is probably a very simple answer if you are familiar with async / tasks but I am still "finding my feet" in this area.

asked Aug 3, 2022 at 0:01
3
  • So what's the problem with the code? Commented Aug 3, 2022 at 3:07
  • nothing actually gets executed Commented Aug 3, 2022 at 3:44
  • 1
    Is the code you posted in the body of a function? How does it look? Can you post the whole function and the way you're calling it? Commented Aug 3, 2022 at 13:21

1 Answer 1

1

Unlike C#'s tasks, Async computation do not start when they are created and you have to explicitly start them. Furthermore, even if you would start the Async operation, it won't do what you expect because the sleep will not execute because you just ignore it.

From the let! in your example code, I'm going to assume you're the code snippet is inside a computation expression. So the following may be what you want

let asyncComputation =
 async {
 let ordersChunked = [] |> List.chunkBySize 5
 for fiveOrders in ordersChunked do
 let! tasks = 
 fiveOrders 
 |> List.map (fun (order) -> trackAndShip(order) )
 |> Async.Parallel
 do! Async.Sleep(1000) // Note the do! here, without it your sleep will be ignored
 }
Async.RunSynchronously asyncComputation

Note that the Async.Sleep is now chained into the CE by using do!. The Async.RunSynchronously call is one way to start the async computation: it runs the async operation and blocks the current thread while waiting for the async operation's result. There are many other ways of running it described in the documentation.

answered Aug 4, 2022 at 5:46
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.