Promise "onCancel" not executing despite promise being cancelled?

I have a chain of promises that run each phase of my game round, each phase is a different function and has an onCancel and a resolve condition, here’s an example:

return Promise.new(function(resolve, reject, onCancel)
		onCancel(function()
			warn("Intermission cancelled")	--Never runs
		end)
		
		IntermissionCountdown.Changed:Connect(function(newTime)
			if newTime <= 0 then
				resolve()
				warn("Intermission phase has ended")
			end
		end)
	end)

Here’s where I cancel the promise.

local myPromise = Promise.new(function(resolve, reject, onCancel)
			Intermission()
			:andThen(Voting)
			:andThen(Hiding)
			:andThen(Round)
			:andThen(Escape)
			:andThen(function()
				resolve()
			end)
		end)
		
		GameStatus.Changed:Connect(function(newValue)
			if newValue == false then
				print("Cancelling promise")
				myPromise:cancel()
			end
		end)

The ‘cancelling promise’ prints so I’m sure it cancels but onCancel never seems to run.

You’re calling the class method cancel() via the colon operator on whatever object the variable “myPromise” points to/refers to. Where is this method’s definition?

Intermission isn’t a chained Promise. Cancellations will propagate upwards and downwards through chains; here, you’re only cancelling the new Promise which encapsulates the Intermission Promise. myPromise has no chained Promises so the cancellation only applies to it.

You would need to cancel the Intermission Promise but chain the subsequent round Promise with finally so that the cancellation doesn’t propagate to the rest of the round Promises. Finally runs regardless of the Promise’s fate which would allow you to sidestep Intermission’s cancellation.

2 Likes