The array of tasks in parallel Ruby

I have a set of tasks that I want to perform sequentially in some background thread, as a result of which each task is transferred to the next, and the chain does not work if any link in the chain fails.

For the argument, suppose that each task is an object with an exec method that returns a value, although they can equally well be proc or lambdas.

Now I have something like:

 promise = array_of_tasks.inject(nil) do |promise, task| if promise promise.then { |prev_result| task.exec(prev_result) } else Concurrent::Promise.new { task.exec } end end promise.on_success { |last_result| log.info("Success: #{last_result} ")} promise.rescue { |reason| log.error("Failure: #{reason}")} 

Is there a shorter way to do this, either in the Promise API or elsewhere in Concurrent Ruby? This seems like a pretty basic operation, but I don't see the existing method that does this.

(Note: if there is no such method, is there a known name for this template in the world of futures and promises? That is, if I write the method myself, are there any obvious names for it?)

+5
source share
1 answer

It is not shorter, but this structure can simplify the addition of new functions:

 require 'concurrent' class Task def exec(x = 0) sleep 0.1 px + 1 end alias call exec def to_promise(*params) Concurrent::Promise.new { exec(*params) } end end module PromiseChains refine Concurrent::Promise do def chained_thens(callables) callables.inject(self) do |promise, callable| promise.then do |prev_result| callable.call(prev_result) end end end end end 

It can be used as follows:

 using PromiseChains array_of_tasks = Array.new(10) { Task.new } array_of_tasks << ->(x) { px * 2 } array_of_tasks << proc { |x| px * 3 } first_task, *other_tasks = array_of_tasks chain = first_task.to_promise.chained_thens(other_tasks) chain.on_success { |last_result| puts "Success: #{last_result} " } chain.rescue { |reason| puts "Failure: #{reason}" } chain.execute sleep(2) 

It outputs:

 1 2 3 4 5 6 7 8 9 10 20 60 Success: 60 
+2
source

Source: https://habr.com/ru/post/1262611/


All Articles