I was working on an app that generated a Markdown article. The article content had some dynamic parts that were fetched via HTTP requests. While not a huge problem, this made the article generation slow.
Ruby 3.0 introduced the fiber scheduler interface, which is used by the async gem to run tasks concurrently. It’s particularly useful for I/O-bound workloads, so I decided to give it a try. This post is a summary of my journey in figuring out how to use it.
This makes each loop async, and the code runs in 3 seconds. Again, we don’t have the values for the paragraphs, just ‘tasks’. Let’s add wait again:
Ok, maybe the problem is using #join right after creating the tasks, which wouldn’t give them time to finish. Against my will, I iteratively built a list:
I was surprised this didn’t work. For some reason, the paragraphs are empty! I thought the Sync block would wait for the internal Async blocks to finish, but it didn’t.