aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2021-03-25 14:28:38 +0000
committerMatthew Wild <mwild1@gmail.com>2021-03-25 14:28:38 +0000
commit2141d9d94a7b0c855a99e4444b093f80ee316f75 (patch)
tree0f3fc3868b801255a9ecfef57847d4ccafbcc315
parent3952fae8ce728d56b9ef2044e490d99a6c12f444 (diff)
downloadprosody-2141d9d94a7b0c855a99e4444b093f80ee316f75.tar.gz
prosody-2141d9d94a7b0c855a99e4444b093f80ee316f75.zip
util.promise: Add join() convenience method
Usage: promise.join(p1, p2, function (result1, result2) [...] end)
-rw-r--r--spec/util_promise_spec.lua26
-rw-r--r--util/promise.lua11
2 files changed, 37 insertions, 0 deletions
diff --git a/spec/util_promise_spec.lua b/spec/util_promise_spec.lua
index 4be9b5a0..79eec5e2 100644
--- a/spec/util_promise_spec.lua
+++ b/spec/util_promise_spec.lua
@@ -459,6 +459,32 @@ describe("util.promise", function ()
assert.same({ foo = true }, result);
end);
end);
+ describe("join()", function ()
+ it("works", function ()
+ local r1, r2;
+ local res1, res2;
+ local p1, p2 = promise.new(function (resolve) r1 = resolve end), promise.new(function (resolve) r2 = resolve end);
+
+ local p = promise.join(p1, p2, function (_res1, _res2)
+ res1, res2 = _res1, _res2;
+ return promise.resolve("works");
+ end);
+
+ local result;
+ local cb = spy.new(function (v)
+ result = v;
+ end);
+ p:next(cb);
+ assert.spy(cb).was_called(0);
+ r2("yep");
+ assert.spy(cb).was_called(0);
+ r1("nope");
+ assert.spy(cb).was_called(1);
+ assert.same("works", result);
+ assert.equals("nope", res1);
+ assert.equals("yep", res2);
+ end);
+ end);
it("promises may be resolved by other promises", function ()
local r1, r2;
local p1, p2 = promise.new(function (resolve) r1 = resolve end), promise.new(function (resolve) r2 = resolve end);
diff --git a/util/promise.lua b/util/promise.lua
index 98d313ba..5996176f 100644
--- a/util/promise.lua
+++ b/util/promise.lua
@@ -2,6 +2,7 @@ local promise_methods = {};
local promise_mt = { __name = "promise", __index = promise_methods };
local xpcall = require "util.xpcall".xpcall;
+local unpack = table.unpack or unpack; --luacheck: ignore 113
function promise_mt:__tostring()
return "promise (" .. (self._state or "invalid") .. ")";
@@ -137,6 +138,15 @@ local function all_settled(promises)
end);
end
+local function join(...)
+ local promises, n = { ... }, select("#", ...);
+ local handler = promises[n];
+ promises[n] = nil;
+ return all(promises):next(function (results)
+ return handler(unpack(results, 1, n - 1));
+ end);
+end
+
local function race(promises)
return new(function (resolve, reject)
for i = 1, #promises do
@@ -180,6 +190,7 @@ end
return {
new = new;
resolve = resolve;
+ join = join;
reject = reject;
all = all;
all_settled = all_settled;