function Promise.race(N)assert(type(N)=="\116\097\098\108\101",string.format(ERROR_NON_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101"))for N,C in pairs(N)do assert(Promise.is(C),string.format(ERROR_NON_PROMISE_IN_LIST,"\080\114\111\109\105\115\101\046\114\097\099\101",tostring(N)))end return Promise._new(debug.traceback(nil,2),function(C,D,Z)local j={}local l=false local function O()for N,C in ipairs(j)do C:cancel()end end local function a(N)return function(...)O()l=true return N(...)end end if Z(a(D))then return end for N,Z in ipairs(N)do j[N]=Z:andThen(a(C),a(D))end if l then O()end end)end
--[=[
	Accepts an array of Promises and returns a new promise that is resolved or rejected as soon as any Promise in the array resolves or rejects.

	:::warning
	If the first Promise to settle from the array settles with a rejection, the resulting Promise from `race` will reject.

	If you instead want to tolerate rejections, and only care about at least one Promise resolving, you should use [Promise.any](#any) or [Promise.some](#some) instead.
	:::

	All other Promises that don't win the race will be cancelled if they have no other consumers.

	```lua
	local promises = {
		returnsAPromise("example 1"),
		returnsAPromise("example 2"),
		returnsAPromise("example 3"),
	}

	return Promise.race(promises) -- Only returns 1st value to resolve or reject
	```

	@param promises {Promise<T>}
	@return Promise<T>
]=]
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
