Make cancellation propagate downstream

This commit is contained in:
Eryn Lynn 2019-09-12 03:58:56 -04:00
parent 7c3ce0f809
commit bf733e642f
8 changed files with 320 additions and 72 deletions

View file

@ -44,7 +44,8 @@ module.exports = {
sidebarDepth: 3,
sidebar: [
'/lib/',
'/lib/Details'
'/lib/Usage',
'/lib/Examples'
]
}
}

12
CHANGELOG.md Normal file
View file

@ -0,0 +1,12 @@
# 2.0.0
- Add Promise.race
- Add Promise.async
- Add Promise.spawn
- Add Promise.promisify
- `finally` now silences the unhandled rejection warning
- `onCancel` now returns if the Promise was cancelled at call time.
- Cancellation now propagates downstream.
- Add `Promise:awaitStatus`
- Calling `resolve` with a Promise while the resolving Promise is cancelled instantly cancels the passed Promise as an optimization.
- `finally` now passes the Promise status as a parameter.

117
lib/Examples.md Normal file
View file

@ -0,0 +1,117 @@
---
title: Examples
---
# Examples
## Chaining
Chain together multiple Promise-returning functions, and only handle a potential error once. If any function rejects in the chain, execution will jump down to `catch`.
```lua
doSomething()
:andThen(doSomethingElse)
:andThen(doSomethingOtherThanThat)
:andThen(doSomethingAgain)
:catch(print)
```
## IsInGroup wrapper
This function demonstrates how to convert a function that yields into a function that returns a Promise. (Assuming you don't want to use <ApiLink to="Promise.promisify" />)
```lua
local function isPlayerInGroup(player, groupId)
return Promise.async(function(resolve)
resolve(player:IsInGroup(groupId))
end)
end
```
## TweenService wrapper
This function demonstrates convert a Roblox API that uses events into a function that returns a Promise.
```lua
local function tween(obj, tweenInfo, props)
return function()
return Promise.new(function(resolve, reject, onCancel)
local tween = TweenService:Create(obj, tweenInfo, props)
if onCancel(function()
tween:Cancel()
end) then return end
tween.Completed:Connect(resolve)
tween:Play()
end)
end
end
```
## Cancellable animation sequence
The following is an example of an animation sequence which is composable and cancellable. If the sequence is cancelled, the animated part will instantly jump to the end position as if it had played all the way through.
We use `finally` instead of `andThen` because we want the Promises to run even if the Promise is cancelled. We handle the case of the Promise being cancelled with the `onCancel` function.
We take advantage of Promise chaining by returning Promises from the `finally` handler functions. Because of this behavior, cancelling the final Promise in the chain will propagate up to the very top and cancel every single Promise you see here.
```lua
local Promise = require(game.ReplicatedStorage.Promise)
local TweenService = game:GetService("TweenService")
local function sleep(seconds)
return function()
return Promise.async(function(resolve)
resolve(wait(seconds))
end)
end
end
local function apply(obj, props)
for key, value in pairs(props) do
obj[key] = value
end
end
local function runTween(obj, props)
return function()
return Promise.new(function(resolve, reject, onCancel)
local tween = TweenService:Create(obj, TweenInfo.new(0.5), props)
if onCancel(function()
tween:Cancel()
apply(obj, props)
end) then return end
tween.Completed:Connect(resolve)
tween:Play()
end)
end
end
local function runAnimation(part, intensity)
return function()
return Promise.resolve()
:finally(sleep(1))
:finally(runTween(part, {
Reflectance = 1 * intensity
})):finally(runTween(part, {
CFrame = CFrame.new(part.Position) *
CFrame.Angles(0, math.rad(90 * intensity), 0)
})):finally(runTween(part, {
Size = (
Vector3.new(10, 10, 10) * intensity
) + Vector3.new(1, 1, 1)
}))
end
end
local animation = Promise.resolve() -- Begin Promise chain
:finally(runAnimation(workspace.Part, 1))
:finally(sleep(1))
:finally(runAnimation(workspace.Part, 0))
wait(2)
animation:cancel() -- Remove this line to see the full animation
```

View file

@ -31,7 +31,7 @@ docs:
Construct a new Promise that will be resolved or rejected with the given callbacks.
::: tip
Generally, it is recommended to use [[Promise.async]] instead. You cannot directly yield inside the `executor` function of [[Promise.new]].
If your Promise executor needs to yield, it is recommended to use [[Promise.async]] instead. You cannot directly yield inside the `executor` function of [[Promise.new]].
:::
If you `resolve` with a Promise, it will be chained onto.
@ -39,6 +39,9 @@ docs:
You may register an optional cancellation hook by using the `onCancel` argument.
* This should be used to abort any ongoing operations leading up to the promise being settled.
* Call the `onCancel` function with a function callback as its only argument to set a hook which will in turn be called when/if the promise is cancelled.
* `onCancel` returns `true` if the Promise was already cancelled when you called `onCancel`.
* Calling `onCancel` with no argument will not override a previously set cancellation hook, but it will still return `true` if the Promise is currently cancelled.
* You can set the cancellation hook at any time before resolving.
* When a promise is cancelled, calls to `resolve` or `reject` will be ignored, regardless of if you set a cancellation hook or not.
static: true
params:
@ -66,15 +69,19 @@ docs:
params:
- name: abortHandler
kind: function
returns: void
returns:
- type: boolean
desc: "Returns `true` if the Promise was already cancelled at the time of calling `onCancel`."
returns: Promise
- name: async
tags: [ 'constructor' ]
desc: |
The same as [[Promise.new]], except it implicitly uses `Promise.spawn` internally. Use this if you want to yield inside your Promise body.
The same as [[Promise.new]], except it implicitly uses [[Promise.spawn]] internally. Use this if you want to yield inside your Promise body.
If your Promise body does not need to yield, such as when attaching `resolve` to an event listener, you should use [[Promise.new]] instead.
::: tip
Promises created with [[Promise.async]] are guaranteed to yield for at least one frame, even if the executor function doesn't yield itself. <a href="/roblox-lua-promise/lib/Details.html#yielding-in-promise-executor">Learn more</a>
Promises created with [[Promise.async]] don't begin executing until the next `RunService.Heartbeat` event, even if the executor function doesn't yield itself. <a href="/roblox-lua-promise/lib/Details.html#yielding-in-promise-executor">Learn more</a>
:::
static: true
params:
@ -102,7 +109,9 @@ docs:
params:
- name: abortHandler
kind: function
returns: void
returns:
- type: boolean
desc: "Returns `true` if the Promise was already cancelled at the time of calling `onCancel`."
returns: Promise
- name: resolve
@ -149,7 +158,37 @@ docs:
params: "...: ...any?"
- name: "..."
type: "...any?"
- name: promisify
desc: |
Wraps a function that yields into one that returns a Promise.
```lua
local sleep = Promise.promisify(wait)
sleep(1):andThen(print)
```
static: true
params:
- name: function
type:
kind: function
params: "...: ...any?"
- name: selfValue
type: any?
desc: This value will be prepended to the arguments list given to the curried function. This can be used to lock a method to a single instance. Otherwise, you can pass the self value before the argument list.
returns:
- desc: The function acts like the passed function but now returns a Promise of its return values.
type:
kind: function
params:
- name: "..."
type: "...any?"
desc: The same arguments the wrapped function usually takes.
returns:
- name: "*"
desc: The return values from the wrapped function.
# Instance methods
- name: andThen
desc: |
Chains onto an existing Promise and returns a new Promise.
@ -210,6 +249,7 @@ docs:
- name: finallyHandler
type:
kind: function
params: "status: PromiseStatus"
returns: ...any?
returns: Promise<...any?>
overloads:
@ -217,6 +257,7 @@ docs:
- name: finallyHandler
type:
kind: function
params: "status: PromiseStatus"
returns: Promise<T>
returns: Promise<T>
@ -231,13 +272,21 @@ docs:
Promises will only be cancelled if all of their consumers are also cancelled. This is to say that if you call `andThen` twice on the same promise, and you cancel only one of the child promises, it will not cancel the parent promise until the other child promise is also cancelled.
- name: await
desc: Yields the current thread until the given Promise completes. Returns `ok` as a bool, followed by the value that the promise returned.
desc: Yields the current thread until the given Promise completes. Returns true if the Promise resolved, followed by the values that the promise resolved or rejected with.
returns:
- desc: Fate of the Promise. `true` if resolved, `false` if rejected, `nil` if cancelled.
type: boolean | nil
- desc: "`true` if the Promise successfully resolved."
type: boolean
- desc: The values that the Promise resolved or rejected with.
type: ...any?
- name: awaitStatus
desc: Yields the current thread until the given Promise completes. Returns the Promise's status, followed by the values that the promise resolved or rejected with.
returns:
- type: PromiseStatus
desc: The Promise's status.
- type: ...any?
desc: The values that the Promise resolved or rejected with.
- name: getStatus
desc: Returns the current Promise status.
returns: PromiseStatus

View file

@ -137,8 +137,8 @@ function Promise.new(callback, parent)
-- length of _values to handle middle nils.
_valuesLength = -1,
-- If an error occurs with no observers, this will be set.
_unhandledRejection = false,
-- Tracks if this Promise has no error observers..
_unhandledRejection = true,
-- Queues representing functions we should invoke when we update!
_queuedResolve = {},
@ -152,12 +152,15 @@ function Promise.new(callback, parent)
-- cancellation propagation.
_parent = parent,
-- The number of consumers attached to this promise. This is needed so that
-- we don't propagate promise cancellations when there are still uncancelled
-- consumers.
_numConsumers = 0,
_consumers = setmetatable({}, {
__mode = "k";
}),
}
if parent and parent._status == Promise.Status.Started then
parent._consumers[self] = true
end
setmetatable(self, Promise)
local function resolve(...)
@ -169,13 +172,15 @@ function Promise.new(callback, parent)
end
local function onCancel(cancellationHook)
assert(type(cancellationHook) == "function", "onCancel must be called with a function as its first argument.")
if self._status == Promise.Status.Cancelled then
cancellationHook()
else
self._cancellationHook = cancellationHook
if cancellationHook then
if self._status == Promise.Status.Cancelled then
cancellationHook()
else
self._cancellationHook = cancellationHook
end
end
return self._status == Promise.Status.Cancelled
end
local _, result = wpcallPacked(callback, resolve, reject, onCancel)
@ -202,15 +207,14 @@ end
Spawns a thread with predictable timing.
]]
function Promise.spawn(callback, ...)
local spawnBindable = Instance.new("BindableEvent")
local args = { ... }
local length = select("#", ...)
spawnBindable.Event:Connect(function()
RunService.Heartbeat:Wait()
local connection
connection = RunService.Heartbeat:Connect(function()
connection:Disconnect()
callback(unpack(args, 1, length))
end)
spawnBindable:Fire()
spawnBindable:Destroy()
end
--[[
@ -328,6 +332,22 @@ function Promise.is(object)
return object[PromiseMarker] == true
end
--[[
Converts a yielding function into a Promise-returning one.
]]
function Promise.promisify(callback, selfValue)
return function(...)
local length, values = pack(...)
return Promise.async(function(resolve)
if selfValue == nil then
resolve(callback(unpack(values, 1, length)))
else
resolve(callback(selfValue, unpack(values, 1, length)))
end
end)
end
end
function Promise.prototype:getStatus()
return self._status
end
@ -339,7 +359,6 @@ end
]]
function Promise.prototype:andThen(successHandler, failureHandler)
self._unhandledRejection = false
self._numConsumers = self._numConsumers + 1
-- Create a new promise to follow this part of the chain
return Promise.new(function(resolve, reject)
@ -397,7 +416,11 @@ function Promise.prototype:cancel()
end
if self._parent then
self._parent:_consumerCancelled()
self._parent:_consumerCancelled(self)
end
for child in pairs(self._consumers) do
child:cancel()
end
self:_finalize()
@ -407,10 +430,14 @@ end
Used to decrease the number of consumers by 1, and if there are no more,
cancel this promise.
]]
function Promise.prototype:_consumerCancelled()
self._numConsumers = self._numConsumers - 1
function Promise.prototype:_consumerCancelled(consumer)
if self._status ~= Promise.Status.Started then
return
end
if self._numConsumers <= 0 then
self._consumers[consumer] = nil
if next(self._consumers) == nil then
self:cancel()
end
end
@ -420,7 +447,7 @@ end
cancelled. Returns a new promise chained from this promise.
]]
function Promise.prototype:finally(finallyHandler)
self._numConsumers = self._numConsumers + 1
self._unhandledRejection = false
-- Return a promise chained off of this promise
return Promise.new(function(resolve, reject)
@ -434,7 +461,7 @@ function Promise.prototype:finally(finallyHandler)
table.insert(self._queuedFinally, finallyCallback)
else
-- The promise already settled or was cancelled, run the callback now.
finallyCallback()
finallyCallback(self._status)
end
end, self)
end
@ -444,45 +471,37 @@ end
This matches the execution model of normal Roblox functions.
]]
function Promise.prototype:await()
function Promise.prototype:awaitStatus()
self._unhandledRejection = false
if self._status == Promise.Status.Started then
local result
local resultLength
local bindable = Instance.new("BindableEvent")
self:andThen(
function(...)
resultLength, result = pack(...)
bindable:Fire(true)
end,
function(...)
resultLength, result = pack(...)
bindable:Fire(false)
end
)
self:finally(function()
bindable:Fire(nil)
bindable:Fire()
end)
local ok = bindable.Event:Wait()
bindable.Event:Wait()
bindable:Destroy()
if ok == nil then
-- If cancelled, we return nil.
return nil
end
return ok, unpack(result, 1, resultLength)
elseif self._status == Promise.Status.Resolved then
return true, unpack(self._values, 1, self._valuesLength)
elseif self._status == Promise.Status.Rejected then
return false, unpack(self._values, 1, self._valuesLength)
end
-- If the promise is cancelled, fall through to nil.
return nil
if self._status == Promise.Status.Resolved then
return self._status, unpack(self._values, 1, self._valuesLength)
elseif self._status == Promise.Status.Rejected then
return self._status, unpack(self._values, 1, self._valuesLength)
end
return self._status
end
--[[
Calls awaitStatus internally, returns (isResolved, values...)
]]
function Promise.prototype:await(...)
local length, result = pack(self:awaitStatus(...))
local status = table.remove(result, 1)
return status == Promise.Status.Resolved, unpack(result, 1, length - 1)
end
--[[
@ -504,6 +523,9 @@ end
function Promise.prototype:_resolve(...)
if self._status ~= Promise.Status.Started then
if Promise.is((...)) then
(...):_consumerCancelled(self)
end
return
end
@ -520,7 +542,7 @@ function Promise.prototype:_resolve(...)
warn(message)
end
(...):andThen(
local promise = (...):andThen(
function(...)
self:_resolve(...)
end,
@ -529,6 +551,14 @@ function Promise.prototype:_resolve(...)
end
)
if promise._status == Promise.Status.Cancelled then
self:cancel()
elseif promise._status == Promise.Status.Started then
-- Adopt ourselves into promise for cancellation propagation.
self._parent = promise
promise._consumers[self] = true
end
return
end
@ -563,7 +593,6 @@ function Promise.prototype:_reject(...)
-- synchronously. We'll wait one tick, and if there are still no
-- observers, then we should put a message in the console.
self._unhandledRejection = true
local err = tostring((...))
spawn(function()
@ -594,8 +623,12 @@ function Promise.prototype:_finalize()
-- Purposefully not passing values to callbacks here, as it could be the
-- resolved values, or rejected errors. If the developer needs the values,
-- they should use :andThen or :catch explicitly.
callback()
callback(self._status)
end
-- Allow family to be buried
self._parent = nil
self._consumers = nil
end
return Promise

View file

@ -334,13 +334,41 @@ return function()
expect(consumer2:getStatus()).to.equal(Promise.Status.Cancelled)
end)
it("should not affect downstream promises", function()
it("should affect downstream promises", function()
local promise = Promise.new(function() end)
local consumer = promise:andThen()
promise:cancel()
expect(consumer:getStatus()).to.equal(Promise.Status.Started)
expect(consumer:getStatus()).to.equal(Promise.Status.Cancelled)
end)
it("should track consumers", function()
local pending = Promise.new(function() end)
local p0 = Promise.resolve()
local p1 = p0:finally(function() return pending end)
local p2 = Promise.new(function(resolve)
resolve(p1)
end)
local p3 = p2:andThen(function() end)
expect(p1._parent).to.never.equal(p0)
expect(p2._parent).to.never.equal(p1)
expect(p2._consumers[p3]).to.be.ok()
expect(p3._parent).to.equal(p2)
end)
it("should cancel resolved pending promises", function()
local p1 = Promise.new(function() end)
local p2 = Promise.new(function(resolve)
resolve(p1)
end):finally(function() end)
p2:cancel()
expect(p1._status).to.equal(Promise.Status.Cancelled)
expect(p2._status).to.equal(Promise.Status.Cancelled)
end)
end)
@ -370,6 +398,14 @@ return function()
expect(callCount).to.equal(5)
end)
it("should be a child of the parent Promise", function()
local p1 = Promise.new(function() end)
local p2 = p1:finally(function() end)
expect(p2._parent).to.equal(p1)
expect(p1._consumers[p2]).to.equal(true)
end)
end)
describe("Promise.all", function()

6
package-lock.json generated
View file

@ -8762,9 +8762,9 @@
}
},
"vuepress-plugin-api-docs-generator": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/vuepress-plugin-api-docs-generator/-/vuepress-plugin-api-docs-generator-1.0.12.tgz",
"integrity": "sha512-ZuBkMrufNOPgDumXL4v0RiXLrdGoFi6d6s5MltVlUnhl1xr3I2uqq3Eootmk5gsVB+VUmfkn0PZC9AAwk3xfEQ==",
"version": "1.0.16",
"resolved": "https://registry.npmjs.org/vuepress-plugin-api-docs-generator/-/vuepress-plugin-api-docs-generator-1.0.16.tgz",
"integrity": "sha512-6D1ZloMemPI3Iyx819ep/mE5+6y5zQ4zw2bM7y0PSUFs68HHbJbxAN9wOoxl9isTvmtTPM19L82E4MkSEzys/w==",
"requires": {
"@vuepress/plugin-register-components": "^1.0.0-rc.1",
"node-balanced": "0.0.14",

View file

@ -9,7 +9,7 @@
"dependencies": {
"gh-pages": "^2.1.1",
"vuepress": "^1.0.3",
"vuepress-plugin-api-docs-generator": "^1.0.12"
"vuepress-plugin-api-docs-generator": "^1.0.16"
},
"devDependencies": {},
"scripts": {