function Promise.race(F)assert(type(F)=="\116\097\098\108\101",string.format(ERROR_NON_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101"))for F,q in pairs(F)do assert(Promise.is(q),string.format(ERROR_NON_PROMISE_IN_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101",tostring(F)))end return Promise._new(debug.traceback(nil,2),function(q,Z,s)local Q={}local N=false local function t()for F,q in ipairs(Q)do q:cancel()end end local function T(F)return function(...)t()N=true return F(...)end end if s(T(Z))then return end for F,s in ipairs(F)do Q[F]=s:andThen(T(q),T(Z))end if N then t()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
