Skip to content

Commit 03a2078

Browse files
Update promise.wait to throw an error when timeout reached or interrupted (#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 <[email protected]> --------- Co-authored-by: Kristijan Husak <[email protected]>
1 parent d4cc321 commit 03a2078

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

lua/orgmode/utils/promise.lua

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ end
263263
--- @param timeout? number
264264
--- @return any
265265
function Promise.wait(self, timeout)
266+
timeout = timeout or 5000
266267
local is_done = false
267268
local has_error = false
268269
local result = nil
@@ -278,7 +279,7 @@ function Promise.wait(self, timeout)
278279
is_done = true
279280
end)
280281

281-
vim.wait(timeout or 5000, function()
282+
local success, code = vim.wait(timeout, function()
282283
return is_done
283284
end, 1)
284285

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

291-
return value
292+
if success then
293+
return value
294+
end
295+
296+
if code == -1 then
297+
return error('promise timeout of ' .. tostring(timeout) .. 'ms reached')
298+
elseif code == -2 then
299+
return error('promise interrupted')
300+
end
301+
302+
return error('promise failed with unknown reason')
292303
end
293304

294305
--- Equivalents to JavaScript's Promise.all.

tests/plenary/utils/promise_spec.lua

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
local Promise = require('orgmode.utils.promise')
2+
3+
describe('Promise', function()
4+
it('should throw an error when wait exceeds its timeout', function()
5+
-- Create a promise that will never resolve or reject
6+
local promise = Promise.new(function() end)
7+
8+
-- We expect an error to occur here when the timeout is exceeded
9+
assert.is.error(function()
10+
-- Provide a smaller timeout so our test doesn't wait 5 seconds
11+
promise:wait(50)
12+
end)
13+
end)
14+
end)

0 commit comments

Comments
 (0)