When a value is no longer needed (e.g., a player closes a menu or an ability is interrupted), you can cancel a Promise. Cancelling a Promise prevents andThen and catch handlers from running.
To stop ongoing work (like a Tween or a network request) when a Promise is cancelled, use the third parameter of the Promise executor, onCancel. This allows you to register a callback that runs specifically when the Promise is cancelled.
If you do not register an onCancel callback, the Promise will stop its chain, but the underlying asynchronous task (like a Tween) will continue to run in the background.
local function tween(obj, tweenInfo, props)
return Promise.new(function(resolve, reject, onCancel)
local tween = TweenService:Create(obj, tweenInfo, props)
-- Register a callback to be called if the Promise is cancelled.
onCancel(function()
tween:Cancel()
end)
tween.Completed:Connect(resolve)
tween:Play()
end)
end
-- Usage
local promise = tween(workspace.Part, TweenInfo.new(2), { Transparency = 0.5 }):andThen(function()
print("This is never printed.")
end):catch(function()
print("This is never printed.")
end):finally(function()
print("But this *is* printed!")
end)
wait(1)
promise:cancel() -- Cancel the Promise, which cancels the tween.