# HG changeset patch # User Matthew Wild # Date 1539861172 -3600 # Node ID 4f4f9823bd1d5721cce9031e4b207fbce7fbc86d # Parent 439cf3bbe5f330fab60b8f330f9b688b24c4303d util.promise: Some code relocation diff -r 439cf3bbe5f3 -r 4f4f9823bd1d util/promise.lua --- a/util/promise.lua Thu Oct 18 12:11:50 2018 +0100 +++ b/util/promise.lua Thu Oct 18 12:12:52 2018 +0100 @@ -55,18 +55,6 @@ return _resolve, _reject; end -local function new(f) - local p = setmetatable({ _state = "pending", _next = next_pending, _pending_on_fulfilled = {}, _pending_on_rejected = {} }, promise_mt); - if f then - local resolve, reject = new_resolve_functions(p); - local ok, ret = pcall(f, resolve, reject); - if not ok and p._state == "pending" then - reject(ret); - end - end - return p; -end - local function wrap_handler(f, resolve, reject) return function (param) local ok, ret = pcall(f, param); @@ -78,17 +66,16 @@ end; end -function promise_methods:next(on_fulfilled, on_rejected) - return new(function (resolve, reject) - self:_next( - on_fulfilled and wrap_handler(on_fulfilled, resolve, reject) or nil, - on_rejected and wrap_handler(on_rejected, resolve, reject) or nil - ); - end); -end - -function promise_methods:catch(on_rejected) - return self:next(nil, on_rejected); +local function new(f) + local p = setmetatable({ _state = "pending", _next = next_pending, _pending_on_fulfilled = {}, _pending_on_rejected = {} }, promise_mt); + if f then + local resolve, reject = new_resolve_functions(p); + local ok, ret = pcall(f, resolve, reject); + if not ok and p._state == "pending" then + reject(ret); + end + end + return p; end local function all(promises) @@ -126,6 +113,19 @@ end); end +function promise_methods:next(on_fulfilled, on_rejected) + return new(function (resolve, reject) --luacheck: ignore 431/resolve 431/reject + self:_next( + on_fulfilled and wrap_handler(on_fulfilled, resolve, reject) or nil, + on_rejected and wrap_handler(on_rejected, resolve, reject) or nil + ); + end); +end + +function promise_methods:catch(on_rejected) + return self:next(nil, on_rejected); +end + return { new = new; resolve = resolve;