function Promise.prototype._finally(h,m,o,j)if not j then h._unhandledRejection=false end return Promise._new(m,function(F,y)local w=F if o then w=createAdvancer(m,o,F,y)end if j then local m=w w=function(...)if h._status==Promise.Status.Rejected then return F(h)end return m(...)end end if h._status==Promise.Status.Started then table.insert(h._queuedFinally,w)else w(h._status)end end,h)end function Promise.prototype.finally(o,m)assert(m==nil or type(m)=="\102\117\110\099\116\105\111\110"or m.__call~=nill,string.format(ERROR_NON_FUNCTION,"\080\114\111\109\105\115\101\058\102\105\110\097\108\108\121"))return o:_finally(debug.traceback(nil,2),m)end

function Promise.prototype:_finally(traceback, finallyHandler, onlyOk)
	if not onlyOk then
		self._unhandledRejection = false
	end

	-- Return a promise chained off of this promise
	return Promise._new(traceback, function(resolve, reject)
		local finallyCallback = resolve
		if finallyHandler then
			finallyCallback = createAdvancer(
				traceback,
				finallyHandler,
				resolve,
				reject
			)
		end

		if onlyOk then
			local callback = finallyCallback
			finallyCallback = function(...)
				if self._status == Promise.Status.Rejected then
					return resolve(self)
				end

				return callback(...)
			end
		end

		if self._status == Promise.Status.Started then
			-- The promise is not settled, so queue this.
			table.insert(self._queuedFinally, finallyCallback)
		else
			-- The promise already settled or was cancelled, run the callback now.
			finallyCallback(self._status)
		end
	end, self)
end

function Promise.prototype:finally(finallyHandler)
	assert(
		finallyHandler == nil or type(finallyHandler) == "function" or finallyHandler.__call ~= nill,
		string.format(ERROR_NON_FUNCTION, "Promise:finally")
	)
	return self:_finally(debug.traceback(nil, 2), finallyHandler)
end
