function Promise.andThen(K,q,y)K._unhandledRejection=false return Promise.new(function(b,d)local c=b if q then c=createAdvancer(q,b,d)end local E=d if y then E=createAdvancer(y,b,d)end if K._status==Promise.Status.Started then table.insert(K._queuedResolve,c)table.insert(K._queuedReject,E)elseif K._status==Promise.Status.Resolved then c(unpack(K._value))elseif K._status==Promise.Status.Rejected then E(unpack(K._value))end end)end

function Promise:andThen(successHandler, failureHandler)
	-- Even if we haven't specified a failure handler, the rejection will be automatically
	-- passed on by the advancer; other promises in the chain may have unhandled rejections,
	-- but this one is taken care of as soon as any andThen is connected
	self._unhandledRejection = false

	-- Create a new promise to follow this part of the chain
	return Promise.new(function(resolve, reject)
		-- Our default callbacks just pass values onto the next promise.
		-- This lets success and failure cascade correctly!

		local successCallback = resolve
		if successHandler then
			successCallback = createAdvancer(successHandler, resolve, reject)
		end

		local failureCallback = reject
		if failureHandler then
			failureCallback = createAdvancer(failureHandler, resolve, reject)
		end

		if self._status == Promise.Status.Started then
			-- If we haven't resolved yet, put ourselves into the queue
			table.insert(self._queuedResolve, successCallback)
			table.insert(self._queuedReject, failureCallback)
		elseif self._status == Promise.Status.Resolved then
			-- This promise has already resolved! Trigger success immediately.
			successCallback(unpack(self._value))
		elseif self._status == Promise.Status.Rejected then
			-- This promise died a terrible death! Trigger failure immediately.
			failureCallback(unpack(self._value))
		end
	end)
end
