aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKim Alvefur <zash@zash.se>2019-01-05 07:08:24 +0100
committerKim Alvefur <zash@zash.se>2019-01-05 07:08:24 +0100
commita35dd91a12ab72517329e810aea69a8f50e09b48 (patch)
tree0deea72cc6035fcfae1cacce7ca0fe8e532a7e6a
parent51c1c97fe262630c37c89579727512bbc52f1249 (diff)
downloadprosody-a35dd91a12ab72517329e810aea69a8f50e09b48.tar.gz
prosody-a35dd91a12ab72517329e810aea69a8f50e09b48.zip
util.promise: Support delayed promise execution
-rw-r--r--spec/util_promise_spec.lua14
-rw-r--r--util/promise.lua17
2 files changed, 26 insertions, 5 deletions
diff --git a/spec/util_promise_spec.lua b/spec/util_promise_spec.lua
index 67f33416..2fd89d03 100644
--- a/spec/util_promise_spec.lua
+++ b/spec/util_promise_spec.lua
@@ -668,4 +668,18 @@ describe("util.promise", function ()
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);
diff --git a/util/promise.lua b/util/promise.lua
index ea30898c..c4e166ed 100644
--- a/util/promise.lua
+++ b/util/promise.lua
@@ -78,14 +78,20 @@ local function new_resolve_functions(p)
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 @@ return {
race = race;
try = try;
is_promise = is_promise;
+ set_nexttick = function(new_next_tick) next_tick = new_next_tick; end;
}