function Promise.race(P)assert(type(P)=="\116\097\098\108\101",string.format(ERROR_NON_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101"))for P,p in pairs(P)do assert(Promise.is(p),string.format(ERROR_NON_PROMISE_IN_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101",tostring(P)))end return Promise._new(debug.traceback(nil,2),function(p,W,u)local Y={}local f=false local function h()for P,p in ipairs(Y)do p:cancel()end end local function O(P)return function(...)h()f=true return P(...)end end if u(O(W))then return end for P,u in ipairs(P)do Y[P]=u:andThen(O(p),O(W))end if f then h()end end)end Promise.Race=Promise.race
--[[
	Races a set of Promises and returns the first one that resolves,
	cancelling the others.
]]
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
