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

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
