util.promise: Add promise.try()

This commit is contained in:
Matthew Wild 2018-10-18 18:03:31 +01:00
parent 44b3954d56
commit 05b4064188
2 changed files with 57 additions and 0 deletions

View file

@ -331,4 +331,55 @@ describe("util.promise", function ()
assert.spy(on_finally_err).was_called_with(test_error);
end);
end);
describe("try()", function ()
it("works with functions that return a promise", function ()
local resolve;
local p = promise.try(function ()
return promise.new(function (_resolve)
resolve = _resolve;
end);
end);
assert.is_function(resolve);
local on_resolved = spy.new(function () end);
p:next(on_resolved);
assert.spy(on_resolved).was_not_called();
resolve("foo");
assert.spy(on_resolved).was_called_with("foo");
end);
it("works with functions that return a value", function ()
local p = promise.try(function ()
return "foo";
end);
local on_resolved = spy.new(function () end);
p:next(on_resolved);
assert.spy(on_resolved).was_called_with("foo");
end);
it("works with functions that return a promise that rejects", function ()
local reject;
local p = promise.try(function ()
return promise.new(function (_, _reject)
reject = _reject;
end);
end);
assert.is_function(reject);
local on_rejected = spy.new(function () end);
p:catch(on_rejected);
assert.spy(on_rejected).was_not_called();
reject("foo");
assert.spy(on_rejected).was_called_with("foo");
end);
it("works with functions that throw errors", function ()
local test_error = {};
local p = promise.try(function ()
error(test_error);
end);
local on_rejected = spy.new(function () end);
p:catch(on_rejected);
assert.spy(on_rejected).was_called(1);
assert.spy(on_rejected).was_called_with(test_error);
end);
end);
end);

View file

@ -51,6 +51,7 @@ local function new_resolve_functions(p)
if resolved then return; end
resolved = true;
if is_promise(e) then
print ("WOAH") assert(false)
e:next(new_resolve_functions(p));
elseif promise_settle(p, "rejected", next_rejected, p._pending_on_rejected, e) then
p.reason = e;
@ -117,6 +118,10 @@ local function reject(v)
end);
end
local function try(f)
return resolve():next(function () return f(); end);
end
function promise_methods:next(on_fulfilled, on_rejected)
return new(function (resolve, reject) --luacheck: ignore 431/resolve 431/reject
self:_next(
@ -142,4 +147,5 @@ return {
reject = reject;
all = all;
race = race;
try = try;
}