function Promise.race(G)assert(type(G)=="\116\097\098\108\101",string.format(ERROR_NON_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101"))for G,E in pairs(G)do assert(Promise.is(E),string.format(ERROR_NON_PROMISE_IN_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101",tostring(G)))end return Promise._new(debug.traceback(nil,2),function(E,x,S)local w={}local s=false local function k()for G,E in ipairs(w)do E:cancel()end end local function D(G)return function(...)k()s=true return G(...)end end if S(D(x))then return end for G,S in ipairs(G)do w[G]=S:andThen(D(E),D(x))end if s then k()end end)end Promise.Race=Promise.race

function Promise.race(promises)
	assert(type(promises) == "table", string.format(ERROR_NON_LIST, "Promise.race"))

	for i, promise in pairs(promises) do
		assert(Promise.is(promise), string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.race", tostring(i)))
	end

	return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
		local newPromises = {}
		local finished = false

		local function cancel()
			for _, promise in ipairs(newPromises) do
				promise:cancel()
			end
		end

		local function finalize(callback)
			return function (...)
				cancel()
				finished = true
				return callback(...)
			end
		end

		if onCancel(finalize(reject)) then
			return
		end

		for i, promise in ipairs(promises) do
			newPromises[i] = promise:andThen(finalize(resolve), finalize(reject))
		end

		if finished then
			cancel()
		end
	end)
end
Promise.Race = Promise.race
