function Promise._all(M,l,v)if type(l)~="\116\097\098\108\101"then error(string.format(ERROR_NON_LIST,"\080\114\111\109\105\115\101\046\097\108\108"),3)end for M,l in pairs(l)do if not Promise.is(l)then error(string.format(ERROR_NON_PROMISE_IN_LIST,"\080\114\111\109\105\115\101\046\097\108\108",tostring(M)),3)end end if#l==0 or v==0 then return Promise.resolve({})end return Promise._new(M,function(M,Z,w)local Y={}local c={}local g=0 local I=0 local N=false local function D()for M,l in ipairs(c)do l:cancel()end end local function R(Z,...)if N then return end g=g+1 if v==nil then Y[Z]=...else Y[g]=...end if g>=(v or#l)then N=true M(Y)D()end end w(D)for M,w in ipairs(l)do c[M]=w:andThen(function(...)R(M,...)end,function(...)I=I+1 if v==nil or#l-I<v then D()N=true Z(...)end end)end if N then D()end end)end

function Promise._all(traceback, promises, amount)
	if type(promises) ~= "table" then
		error(string.format(ERROR_NON_LIST, "Promise.all"), 3)
	end

	-- We need to check that each value is a promise here so that we can produce
	-- a proper error rather than a rejected promise with our error.
	for i, promise in pairs(promises) do
		if not Promise.is(promise) then
			error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3)
		end
	end

	-- If there are no values then return an already resolved promise.
	if #promises == 0 or amount == 0 then
		return Promise.resolve({})
	end

	return Promise._new(traceback, function(resolve, reject, onCancel)
		-- An array to contain our resolved values from the given promises.
		local resolvedValues = {}
		local newPromises = {}

		-- Keep a count of resolved promises because just checking the resolved
		-- values length wouldn't account for promises that resolve with nil.
		local resolvedCount = 0
		local rejectedCount = 0
		local done = false

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

		-- Called when a single value is resolved and resolves if all are done.
		local function resolveOne(i, ...)
			if done then
				return
			end

			resolvedCount = resolvedCount + 1

			if amount == nil then
				resolvedValues[i] = ...
			else
				resolvedValues[resolvedCount] = ...
			end

			if resolvedCount >= (amount or #promises) then
				done = true
				resolve(resolvedValues)
				cancel()
			end
		end

		onCancel(cancel)

		-- We can assume the values inside `promises` are all promises since we
		-- checked above.
		for i, promise in ipairs(promises) do
			newPromises[i] = promise:andThen(
				function(...)
					resolveOne(i, ...)
				end,
				function(...)
					rejectedCount = rejectedCount + 1

					if amount == nil or #promises - rejectedCount < amount then
						cancel()
						done = true

						reject(...)
					end
				end
			)
		end

		if done then
			cancel()
		end
	end)
end
