 	then: (onFulfilled, onRejected) ->
 		self = @
 
+		if @_state == $pending
+			@_thenIndex++
+
+		thenIndex = @_thenIndex
+
+		addHandler self, thenIndex, onFulfilled, onRejected
+
 		new Promise (resolve, reject) ->
-			addTrigger self, onFulfilled, resolve, onRejected, reject
+			chainHandlers self, thenIndex, resolve, reject
 
 	catch: (onRejected) ->
 

		self._state = state
		self._value = value
		i = 0

		while i < self._thenCount
			# Trick: we reuse the value of state as the handler selector.
			k = i++ * 4 + state

			chainHandler value, self._handlers[k], self._handlers[k + 1]

		return

	run = (self, executor) -> nextTick ->
		executor genTrigger(self, $resolved),
			genTrigger(self, $rejected)
		return

	addHandler = (self, thenIndex, onFulfilled, onRejected) ->
		switch self._state
			when $pending
				self._handlers.splice self._handlers.length - 1, 0,
					onFulfilled, onRejected

			when $resolved
				self._handlers.splice thenIndex * 4, 0,
					onFulfilled(self._value)

			when $rejected
				self._handlers.splice thenIndex * 4 + 1, 0,
					onRejected(self._value)
		return

	chainHandlers = (self, thenIndex, resolve, reject) ->
		switch self._state
			when $pending
				self._handlers.splice thenIndex * 4 + 2, 0,
					resolve, reject

			when $resolved
				chainHandler self._handlers[thenIndex * 4], 0, resolve

			when $rejected
				chainHandler self._handlers[thenIndex * 4 + 1], 0, reject

		return

	chainHandler = (value, handler) ->
		if value and typeof value.then == 'function'
			value.then handler
		else
			handler value
		return

	genTrigger = (self, state) -> (value) ->
		if self._state != $pending
