 	# It only counts when the current promise is on pending state.
 	_thenCount: 0
 
+	$resolveSelf = 'Promise cannot resolve itself.'
+
 	nextTick = do ->
 		(fn) ->
 			process.nextTick fn

	addHandler = (self, onFulfilled, onRejected, resolve, reject) ->
		offset = self._thenCount * 4

		switch self._state
			when $pending
				self._handlers[offset] = onFulfilled
				self._handlers[offset + 1] = onRejected
				self._handlers[offset + 2] = resolve
				self._handlers[offset + 3] = reject
				self._thenCount++

			when $resolved
				chainHandler self._value, onFulfilled, resolve

			when $rejected
				chainHandler self._value, onRejected, reject
		return

	# Chain value to a handler, then handler may be a promise or a function.
	chainHandler = (value, onFulfilled, onRejected) ->
		if value and typeof value.then == 'function'
			value.then onFulfilled, onRejected
		else
			onFulfilled value
		return

	# It will produce a trigger function to user.
	# Such as the resolve and reject in this `new Promise (resolve, reject) ->`.

		self._state = state
		self._value = value

		offset = 0
		len = self._thenCount * 4

		while offset < len
			chainHandler self, offset

			offset += 4

		return
