I would like to pass in arguments to the function I pass into Task.async, but there’s no Task.async/2. Why is this?
1 Like
The idiom is to simply create a new anonymous function which uses the arguments captured in the closure - and pass that to Task.async
.
task = Task.async(fn -> do_some_work(arg1,arg2,arg3) end)
Task.Async/3
simply follows the Module/Function/Arguments (mfa) convention of Kernel.apply/3
- but the “function” is an atom representing the function name rather than an actual function.
Kernel.apply/2 is primarily used in situations where the intention is to use the same (configurable) function with different arguments.
When you are spawning a task you are expected to bring together the function and arguments you need - so it makes sense to combine them in an anonymous function.
6 Likes