 	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) ->
 

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

	addTrigger = (self, onFulfilled, resolve, onRejected, reject) ->
		switch self._state
			when $pending
				self._thenCount++
				self._handlers.splice self._handlers - 1, 0,
					onFulfilled, resolve, onRejected, reject

			when $resolved
				chainHandler self._value, onFulfilled, resolve

			when $rejected
				chainHandler self._value, onRejected, reject

	chainHandler = (value, handler, thenHandler) ->
		out = handler value

		if out and typeof out.then == 'function'
			out.then thenHandler
		else
			thenHandler out

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

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

		while i < len
			# Trick: Reuse the value of state as the handler selector.
			k = i++ * 4 + state

			thenHandler = self._handlers[k + 2]

			if thenHandler
				chainHandler self._handlers[k](value), thenHandler
			else
				self._handlers[k] = self._handlers[k] value

		return
