Make promisify catch errors

Closes #12
This commit is contained in:
Eryn Lynn 2019-09-28 17:38:35 -04:00
parent 65daff4777
commit c0626c0baf
4 changed files with 27 additions and 2 deletions

View file

@ -5,6 +5,8 @@
- Fix issue with Promise.race/all always cancelling instead of only cancelling if the Promise has no other consumers
- Make error checking more robust across many methods.
- Promise.Status members are now strings instead of symbols, and indexing a non-existent value will error.
- Improve stack traces
- Promise.promisify will now turn errors into rejections even if they occur after a yield.
# 2.4.0

View file

@ -129,6 +129,8 @@ docs:
desc: |
Wraps a function that yields into one that returns a Promise.
Any errors that occur while executing the function will be turned into rejections.
```lua
local sleep = Promise.promisify(wait)

View file

@ -368,10 +368,16 @@ end
]]
function Promise.promisify(callback)
return function(...)
local traceback = debug.traceback()
local length, values = pack(...)
return Promise.new(function(resolve)
return Promise.new(function(resolve, reject)
coroutine.wrap(function()
resolve(callback(unpack(values, 1, length)))
local ok, resultLength, resultValues = packResult(pcall(callback, unpack(values, 1, length)))
if ok then
resolve(unpack(resultValues, 1, resultLength))
else
reject((resultValues[1] or "error") .. "\n" .. traceback)
end
end)()
end)
end

View file

@ -624,6 +624,21 @@ return function()
expect(status).to.equal(Promise.Status.Resolved)
expect(result).to.equal(2)
end)
it("should catch errors after a yield", function()
local bindable = Instance.new("BindableEvent")
local test = Promise.promisify(function ()
bindable.Event:Wait()
error('errortext')
end)
local promise = test()
expect(promise:getStatus()).to.equal(Promise.Status.Started)
bindable:Fire()
expect(promise:getStatus()).to.equal(Promise.Status.Rejected)
expect(promise._values[1]:find("errortext")).to.be.ok()
end)
end)
describe("Promise.tap", function()