Software /
code /
prosody
Comparison
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 |
comparison
equal
deleted
inserted
replaced
11483:24ce9d380475 | 11484:a0120e935442 |
---|---|
1 local promise_methods = {}; | 1 local promise_methods = {}; |
2 local promise_mt = { __name = "promise", __index = promise_methods }; | 2 local promise_mt = { __name = "promise", __index = promise_methods }; |
3 | 3 |
4 local xpcall = require "util.xpcall".xpcall; | 4 local xpcall = require "util.xpcall".xpcall; |
5 local unpack = table.unpack or unpack; --luacheck: ignore 113 | |
5 | 6 |
6 function promise_mt:__tostring() | 7 function promise_mt:__tostring() |
7 return "promise (" .. (self._state or "invalid") .. ")"; | 8 return "promise (" .. (self._state or "invalid") .. ")"; |
8 end | 9 end |
9 | 10 |
135 resolve(results); | 136 resolve(results); |
136 end | 137 end |
137 end); | 138 end); |
138 end | 139 end |
139 | 140 |
141 local function join(...) | |
142 local promises, n = { ... }, select("#", ...); | |
143 local handler = promises[n]; | |
144 promises[n] = nil; | |
145 return all(promises):next(function (results) | |
146 return handler(unpack(results, 1, n - 1)); | |
147 end); | |
148 end | |
149 | |
140 local function race(promises) | 150 local function race(promises) |
141 return new(function (resolve, reject) | 151 return new(function (resolve, reject) |
142 for i = 1, #promises do | 152 for i = 1, #promises do |
143 promises[i]:next(resolve, reject); | 153 promises[i]:next(resolve, reject); |
144 end | 154 end |
178 end | 188 end |
179 | 189 |
180 return { | 190 return { |
181 new = new; | 191 new = new; |
182 resolve = resolve; | 192 resolve = resolve; |
193 join = join; | |
183 reject = reject; | 194 reject = reject; |
184 all = all; | 195 all = all; |
185 all_settled = all_settled; | 196 all_settled = all_settled; |
186 race = race; | 197 race = race; |
187 try = try; | 198 try = try; |