Diff

util/promise.lua @ 11484:a0120e935442

util.promise: Add join() convenience method Usage: promise.join(p1, p2, function (result1, result2) [...] end)
author Matthew Wild <mwild1@gmail.com>
date Thu, 25 Mar 2021 14:28:38 +0000
parent 11483:24ce9d380475
child 11485:7d42ed3a8a40
line wrap: on
line diff
--- a/util/promise.lua	Thu Mar 25 13:51:16 2021 +0000
+++ b/util/promise.lua	Thu Mar 25 14:28:38 2021 +0000
@@ -2,6 +2,7 @@
 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 @@
 	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 @@
 return {
 	new = new;
 	resolve = resolve;
+	join = join;
 	reject = reject;
 	all = all;
 	all_settled = all_settled;