Skip to content

Update promise.wait to throw an error when timeout reached or interrupted #723

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions lua/orgmode/utils/promise.lua
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ end
--- @param timeout? number
--- @return any
function Promise.wait(self, timeout)
timeout = timeout or 5000
local is_done = false
local has_error = false
local result = nil
Expand All @@ -278,7 +279,7 @@ function Promise.wait(self, timeout)
is_done = true
end)

vim.wait(timeout or 5000, function()
local success, code = vim.wait(timeout, function()
return is_done
end, 1)

Expand All @@ -288,7 +289,17 @@ function Promise.wait(self, timeout)
return error(value)
end

return value
if success then
return value
end

if code == -1 then
return error('promise timeout of ' .. tostring(timeout) .. 'ms reached')
elseif code == -2 then
return error('promise interrupted')
end

return error('promise failed with unknown reason')
end

--- Equivalents to JavaScript's Promise.all.
Expand Down
14 changes: 14 additions & 0 deletions tests/plenary/utils/promise_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
local Promise = require('orgmode.utils.promise')

describe('Promise', function()
it('should throw an error when wait exceeds its timeout', function()
-- Create a promise that will never resolve or reject
local promise = Promise.new(function() end)

-- We expect an error to occur here when the timeout is exceeded
assert.is.error(function()
-- Provide a smaller timeout so our test doesn't wait 5 seconds
promise:wait(50)
end)
end)
end)
Loading