Skip to content

Commit

Permalink
Add Executor.join_async() method
Browse files Browse the repository at this point in the history
  • Loading branch information
epwalsh committed Nov 6, 2023
1 parent 5d302b6 commit 41b7356
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions lua/obsidian/async.lua
Original file line number Diff line number Diff line change
Expand Up @@ -88,27 +88,42 @@ Executor.map = function(self, fn, task_args, callback)
end
end

---Block Neovim until all currently running tasks have completed, waiting at most `timeout` milliseconds
---before raising a timeout error.
---
---This is useful in testing, but in general you want to avoid blocking Neovim.
---
---@param self obsidian.Executor
---@param timeout integer|?
Executor.join = function(self, timeout)
---@param pause_fn function(integer)
Executor._join = function(self, timeout, pause_fn)
local start_time = uv.uptime()
local pause_for = 100
if timeout ~= nil then
pause_for = math.min(timeout / 2, pause_for)
end
while self.tasks_running > 0 do
vim.wait(pause_for)
pause_fn(pause_for)
if timeout ~= nil and uv.uptime() - start_time > timeout then
error "Timeout error from AsyncExecutor.join()"
end
end
end

---Block Neovim until all currently running tasks have completed, waiting at most `timeout` milliseconds
---before raising a timeout error.
---
---This is useful in testing, but in general you want to avoid blocking Neovim.
---
---@param self obsidian.Executor
---@param timeout integer|?
Executor.join = function(self, timeout)
self:_join(timeout, vim.wait)
end

---An async version of `.join()`.
---
---@param self obsidian.Executor
---@param timeout integer|?
Executor.join_async = function(self, timeout)
self:_join(timeout, async.util.sleep)
end

---An Executor that uses coroutines to run user functions concurrently.
---@class obsidian.AsyncExecutor : obsidian.Executor
---@field tasks_running integer
Expand Down

0 comments on commit 41b7356

Please sign in to comment.