Skip to content

Commit

Permalink
Update promise.wait to throw an error when timeout reached or interru…
Browse files Browse the repository at this point in the history
…pted (#723)

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

* Revert some formatting changes

* Fix lint error

* Add test to demonstrate functionality

* Update lua/orgmode/utils/promise.lua

Co-authored-by: Kristijan Husak <husakkristijan@gmail.com>

---------

Co-authored-by: Kristijan Husak <husakkristijan@gmail.com>
  • Loading branch information
chipsenkbeil and kristijanhusak authored May 6, 2024
1 parent d4cc321 commit 03a2078
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
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)

0 comments on commit 03a2078

Please sign in to comment.