Software /
code /
prosody
Changeset
11947:073e53b72792
util.promise: Support delayed promise execution
author | Kim Alvefur <zash@zash.se> |
---|---|
date | Sat, 05 Jan 2019 07:08:24 +0100 |
parents | 11946:c0a01e5f5656 |
children | 11948:dca75cc6fc5a |
files | spec/util_promise_spec.lua util/promise.lua |
diffstat | 2 files changed, 26 insertions(+), 5 deletions(-) [+] |
line wrap: on
line diff
--- a/spec/util_promise_spec.lua Fri Nov 26 11:40:48 2021 +0100 +++ b/spec/util_promise_spec.lua Sat Jan 05 07:08:24 2019 +0100 @@ -668,4 +668,18 @@ assert.spy(on_rejected).was_called_with(test_error); end); end); + describe("set_nexttick()", function () + it("works", function () + local next_tick = spy.new(function (f) + f(); + end) + local cb = spy.new(); + promise.set_nexttick(next_tick); + promise.new(function (y, _) + y("okay"); + end):next(cb); + assert.spy(next_tick).was.called(); + assert.spy(cb).was.called_with("okay"); + end); + end) end);
--- a/util/promise.lua Fri Nov 26 11:40:48 2021 +0100 +++ b/util/promise.lua Sat Jan 05 07:08:24 2019 +0100 @@ -78,14 +78,20 @@ return _resolve, _reject; end +local next_tick = function (f) + f(); +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 = xpcall(f, debug.traceback, resolve, reject); - if not ok and p._state == "pending" then - reject(ret); - end + next_tick(function() + local resolve, reject = new_resolve_functions(p); + local ok, ret = xpcall(f, debug.traceback, resolve, reject); + if not ok and p._state == "pending" then + reject(ret); + end + end); end return p; end @@ -203,4 +209,5 @@ race = race; try = try; is_promise = is_promise; + set_nexttick = function(new_next_tick) next_tick = new_next_tick; end; }