I have a set of tasks that I want to execute sequentially in some background thread, with the result of each task being passed to the next, and with the chain failing if any link in the chain fails.
For the sake of argument, let's say each task is an object with an exec
method that returns a value, although they could equally well be procs or lambdas.
What I have now is 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 more concise way to do this, either in the Promise
API or elsewhere in Concurrent Ruby? It seems like a fairly basic operation, but I'm not seeing an existing method that does it.
(Side note: if there isn't such a method, is there a well-known name for this pattern in the futures-and-promises world? I.e., if I write the method myself, is there some existing obvious name for it?)