Update for release

This commit is contained in:
Eryn Lynn 2019-09-10 15:34:06 -04:00
parent 6a3531de1e
commit 9a1d1c3530
12 changed files with 9600 additions and 63 deletions

3
.gitignore vendored
View file

@ -1 +1,2 @@
/luacov.*.out
/luacov.*.out
node_modules/

48
.vuepress/config.js Normal file
View file

@ -0,0 +1,48 @@
module.exports = {
title: 'Roblox Lua Promise',
description: 'Promise implementation for Roblox',
base: '/roblox-lua-promise/',
plugins: [
['api-docs-generator', {
defaults: {
returns: ['void'],
property_tags: [{
name: 'read only',
unless: ['writable']
}]
},
types: {
void: {
summary: 'Interchangeable for nil in most cases.'
},
},
tagColors: {
'read only': '#1abc9c',
'writable': '#3498db',
'deprecated': '#e7c000',
'client only': '#349AD5',
'server only': '#01CC67',
'enums': '#e67e22'
},
methodCallOperator: ':',
staticMethodCallOperator: '.'
}]
],
themeConfig: {
searchOptions: {
placeholder: 'Press S to search...'
},
nav: [
{ text: 'API Reference', link: '/lib/' }
],
sidebarDepth: 3,
sidebar: [
'/lib/',
'/lib/Details'
]
}
}

View file

@ -0,0 +1 @@
$accentColor = #9b59b6

View file

@ -1,56 +1,30 @@
---
home: true
actionText: API docs →
actionLink: /lib/
footer: MIT Licensed
---
# Roblox Lua Promise
An implementation of `Promise` similar to Promise/A+.
## Motivation
I've found that being able to yield anywhere causes lots of bugs. In [Rodux](https://github.com/Roblox/Rodux), I explicitly made it impossible to yield in a change handler because of the sheer number of bugs that occured when callbacks randomly yielded.
As such, I think that Roblox needs an object-based async primitive. It's not important to me whether these are Promises, Observables, Task objects, or Futures.
The way Roblox models asynchronous operations by default is by yielding (stopping) the thread and then resuming it when the future value is available. This model is not ideal because:
The important traits are:
- Functions you call can yield without warning, or only yield sometimes, leading to unpredictable and surprising results. Accidentally yielding the thread is the source of a large class of bugs and race conditions that Roblox developers run into.
- It is difficult to deal with running multiple asynchronous operations concurrently and then retrieve all of their values at the end without extraneous machinery.
- When an asynchronous operation fails or an error is encountered, Lua functions usually either raise an error or return a success value followed by the actual value. Both of these methods lead to repeating the same tired patterns many times over for checking if the operation was successful.
- Yielding lacks easy access to introspection and the ability to cancel an operation if the value is no longer needed.
### Goals
This Promise implementation attempts to satisfy these traits:
* An object that represents a unit of asynchronous work
* Composability
* Predictable timing
This Promise implementation attempts to satisfy those traits.
## API
### Static Functions
* `Promise.new((resolve, reject, onCancel) -> nil) -> Promise`
* Construct a new Promise that will be resolved or rejected with the given callbacks.
* 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.
* When a promise is cancelled, calls to `resolve` or `reject` will be ignored, regardless of if you set a cancellation hook or not.
* `Promise.resolve(value) -> Promise`
* Creates an immediately resolved Promise with the given value.
* `Promise.reject(value) -> Promise`
* Creates an immediately rejected Promise with the given value.
* `Promise.is(object) -> bool`
* Returns whether the given object is a Promise.
* `Promise.all(array) -> array`
* Accepts an array of promises and returns a new promise that:
* is resolved after all input promises resolve.
* is rejected if ANY input promises reject.
* Note: Only the first return value from each promise will be present in the resulting array.
### Instance Methods
* `Promise:andThen(successHandler, [failureHandler]) -> Promise`
* Chains onto an existing Promise and returns a new Promise.
* Equivalent to the Promise/A+ `then` method.
* `Promise:catch(failureHandler) -> Promise`
* Shorthand for `Promise:andThen(nil, failureHandler)`.
* `Promise:finally(finallyHandler) -> Promise`
* Set a handler that will be called regardless of the promise's fate. The handler is called when the promise is resolved, rejected, *or* cancelled.
* Returns a new promise chained from this promise.
* `Promise:cancel() -> nil`
* Cancels this promise, preventing the promise from resolving or rejecting. Does not do anything if the promise is already settled.
* Cancellations will propagate upwards through chained promises.
* 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 promises resulting from the `andThen` call, it will not cancel the parent promise until the other child promise is also cancelled.
* `Promise:await() -> ok, value`
* Yields the current thread until the given Promise completes. Returns `ok` as a bool, followed by the value that the promise returned.
## Example
This Promise implementation finished synchronously. In order to wrap an existing async API, you should use `spawn` or `delay` in order to prevent your calling thread from accidentally yielding.
@ -61,8 +35,7 @@ local HttpService = game:GetService("HttpService")
-- Ideally, you do this once per project per async method that you use.
local function httpGet(url)
return Promise.new(function(resolve, reject)
-- Spawn to prevent yielding, since GetAsync yields.
spawn(function()
Promise.spawn(function()
local ok, result = pcall(HttpService.GetAsync, HttpService, url)
if ok then
@ -83,10 +56,3 @@ httpGet("https://google.com")
warn("We failed to get the Google homepage!", err)
end)
```
## Future Additions
* `Promise.wrapAsync`
* Intended to wrap an existing Roblox API that yields, exposing a new one that returns a Promise.
## License
This project is available under the CC0 license. See [LICENSE](LICENSE) for details.

12
default.project.json Normal file
View file

@ -0,0 +1,12 @@
{
"name": "lua-promise",
"tree": {
"$className": "DataModel",
"ReplicatedStorage": {
"$className": "ReplicatedStorage",
"Promise": {
"$path": "lib"
}
}
}
}

48
lib/Details.md Normal file
View file

@ -0,0 +1,48 @@
---
title: Implementation Details
---
# Implementation Details
## Yielding in Promise executor
If you need to yield in the Promise executor, you must wrap your yielding code in a new thread to prevent your calling thread from yielding. The easiest way to do this is to wrap your code with the built-in `Promise.spawn`:
```lua
Promise.new(function(resolve)
Promise.spawn(function()
wait(1)
resolve()
end)
end)
```
`Promise.spawn` uses a BindableEvent internally to launch your Promise body on a fresh thread after waiting for the next `RunService.Heartbeat` event.
The reason `Promise.spawn` includes this wait time is to ensure that your Promises have consistent timing. Otherwise, your Promise would run synchronously up to the first yield, and asynchronously afterwards. This can often lead to undesirable results. Additionally, Promises that never yield can resolve completely synchronously, and this can lead to unpredictable timing issues. Thus, we use `Promise.spawn` so there is always a guaranteed yield before execution.
::: danger Don't use regular spawn
`spawn` might seem like a tempting alternative to `Promise.spawn` here, but you should **never** use it!
`spawn` (and `wait`, for that matter) do not resume threads at a consistent interval. If Roblox has resumed too many threads in a single Lua step, it will begin throttling and your thread that was meant to be resumed on the next frame could actually be resumed several seconds later. The unexpected delay caused by this behavior will cause cascading timing issues in your game and could lead to some potentially ugly bugs.
:::
::: warning coroutine.wrap would work, but...
`coroutine.wrap` is another possible stand-in for creating a BindableEvent and firing it off, but in the case of an error, the stack trace is reset when the coroutine executes. This can make troubleshooting extremely difficult because you don't know where to look in your code base for the source of the error. Creating a BindableEvent is relatively cheap, so you shouldn't need to worry about this causing performance problems in your game.
:::
## Cancellation details
If a Promise is already cancelled at the time of calling its onCancel hook, the hook will be called immediately.
If you attach a `:andThen` or `:catch` handler to a Promise after it's been cancelled, the chained Promise will be instantly rejected with the error "Promise is cancelled".
If you cancel a Promise immediately after creating it in the same Lua cycle, the fate of the Promise is dependent on if the Promise handler yields or not. If the Promise handler resolves without yielding, then the Promise will already be settled by the time you are able to cancel it, thus any consumers of the Promise will have already been called.
If the Promise does yield, then cancelling it immediately *will* prevent its resolution. This is always the case when using `Promise.spawn`.
Attempting to cancel an already-settled Promise is ignored.
### Cancellation propagation
When you cancel a Promise, the cancellation propagates up the Promise chain. Promises keep track of the number of consumers that they have, and when the upwards propagation encounters a Promise that no longer has any consumers, that Promise is cancelled as well.
It's important to note that cancellation does **not** propagate downstream, so if you get a handle to a Promise earlier in the chain and cancel it directly, Promises that are consuming the cancelled Promise will remain in an unsettled state forever.

197
lib/README.md Normal file
View file

@ -0,0 +1,197 @@
---
title: Promise
docs:
desc: A Promise is an object that represents a value that will exist in the future, but doesn't right now. Promises allow you to then attach callbacks that can run once the value becomes available (known as *resolving*), or if an error has occurred (known as *rejecting*).
types:
- name: PromiseStatus
desc: An enum value used to represent the Promise's status.
kind: enum
type:
Started:
desc: The Promise is executing, and not settled yet.
Resolved:
desc: The Promise finished successfully.
Rejected:
desc: The Promise was rejected.
Cancelled:
desc: The Promise was cancelled before it finished.
properties:
- name: Status
tags: [ 'read only', 'static', 'enums' ]
type: PromiseStatus
functions:
- name: new
desc: |
Construct a new Promise that will be resolved or rejected with the given callbacks.
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.
* 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:
- name: executor
type:
kind: function
params:
- name: resolve
type:
kind: function
params:
- name: "..."
type: ...any?
returns: void
- name: reject
type:
kind: function
params:
- name: "..."
type: ...any?
returns: void
- name: onCancel
type:
kind: function
params:
- name: abortHandler
kind: function
returns: void
- name: resolve
desc: Creates an immediately resolved Promise with the given value.
static: true
params: "value: T"
returns: Promise<T>
- name: reject
desc: Creates an immediately rejected Promise with the given value.
static: true
params: "value: T"
returns: Promise<T>
- name: all
desc: |
Accepts an array of Promises and returns a new promise that:
* is resolved after all input promises resolve.
* is rejected if ANY input promises reject.
Note: Only the first return value from each promise will be present in the resulting array.
static: true
params: "promises: array<Promise<T>>"
returns: Promise<array<T>>
- name: race
desc: |
Accepts an array of Promises and returns a new promise that is resolved or rejected as soon as any Promise in the array resolves or rejects.
All other Promises that don't win the race will be cancelled.
static: true
params: "promises: array<Promise<T>>"
returns: Promise<T>
- name: is
desc: Returns whether the given object is a Promise.
static: true
params: "object: any"
returns:
- type: boolean
desc: "`true` if the given `object` is a Promise."
- name: spawn
desc: Spawns a thread with predictable timing. The callback will be called on the next `RunService.Stepped` event.
static: true
params:
- name: callback
type:
kind: function
params: "...: ...any?"
- name: "..."
type: "...any?"
- name: andThen
desc: Chains onto an existing Promise and returns a new Promise.
params:
- name: successHandler
type:
kind: function
params: "...: ...any?"
returns: ...any?
- name: failureHandler
optional: true
type:
kind: function
params: "...: ...any?"
returns: ...any?
returns: Promise<...any?>
overloads:
- params:
- name: successHandler
type:
kind: function
params: "...: ...any?"
returns: Promise<T>
- name: failureHandler
optional: true
type:
kind: function
params: "...: ...any?"
returns: Promise<T>
returns: Promise<T>
- name: catch
desc: Shorthand for `Promise:andThen(nil, failureHandler)`.
params:
- name: failureHandler
type:
kind: function
params: "...: ...any?"
returns: ...any?
returns: Promise<...any?>
overloads:
- params:
- name: failureHandler
type:
kind: function
params: "...: ...any?"
returns: Promise<T>
returns: Promise<T>
- name: finally
desc: |
Set a handler that will be called regardless of the promise's fate. The handler is called when the promise is resolved, rejected, *or* cancelled.
Returns a new promise chained from this promise.
params:
- name: finallyHandler
type:
kind: function
returns: ...any?
returns: Promise<...any?>
overloads:
- params:
- name: finallyHandler
type:
kind: function
returns: Promise<T>
returns: Promise<T>
- name: cancel
desc: |
Cancels this promise, preventing the promise from resolving or rejecting. Does not do anything if the promise is already settled.
Cancellations will propagate upwards through chained promises.
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.
returns:
- desc: Fate of the Promise. `true` if resolved, `false` if rejected, `nil` if cancelled.
type: boolean | nil
- desc: The values that the Promise resolved or rejected with.
type: ...any?
- name: getStatus
desc: Returns the current Promise status.
returns: PromiseStatus
---
<ApiDocs />

View file

@ -2,6 +2,7 @@
An implementation of Promises similar to Promise/A+.
]]
local RunService = game:GetService("RunService")
local PROMISE_DEBUG = false
--[[
@ -188,6 +189,21 @@ function Promise.new(callback, parent)
return self
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()
callback(unpack(args, 1, length))
end)
spawnBindable:Fire()
spawnBindable:Destroy()
end
--[[
Create a promise that represents the immediately resolved value.
]]
@ -262,6 +278,36 @@ function Promise.all(promises)
end)
end
--[[
Races a set of Promises and returns the first one that resolves,
cancelling the others.
]]
function Promise.race(promises)
assert(type(promises) == "table", "Please pass a list of promises to Promise.race")
for i, promise in ipairs(promises) do
assert(Promise.is(promise), ("Non-promise value passed into Promise.race at index #%d"):format(i))
end
return Promise.new(function(resolve, reject, onCancel)
local function finalize(callback)
return function (...)
for _, promise in ipairs(promises) do
promise:cancel()
end
return callback(...)
end
end
onCancel(finalize(reject))
for _, promise in ipairs(promises) do
promise:andThen(finalize(resolve), finalize(reject))
end
end)
end
--[[
Is the given object a Promise instance?
]]

View file

@ -72,10 +72,11 @@ return function()
expect(promise:getStatus()).to.equal(Promise.Status.Rejected)
expect(promise._values[1]:find("hahah")).to.be.ok()
-- Loosely check for the pieces of the stack trace we expect
expect(promise._values[1]:find("init.spec")).to.be.ok()
expect(promise._values[1]:find("new")).to.be.ok()
expect(promise._values[1]:find("error")).to.be.ok()
expect(promise._values[1]:find("Stack Begin")).to.be.ok()
end)
end)
@ -514,4 +515,35 @@ return function()
expect(second).to.equal("bar")
end)
end)
describe("Promise.race", function()
it("should resolve with the first settled value", function()
local promise = Promise.race({
Promise.resolve(1),
Promise.resolve(2)
}):andThen(function(value)
expect(value).to.equal(1)
end)
expect(promise:getStatus()).to.equal(Promise.Status.Resolved)
end)
it("should cancel other promises", function()
local promises = {
Promise.new(function(resolve)
-- resolve(1)
end),
Promise.new(function(resolve)
resolve(2)
end)
}
local promise = Promise.race(promises)
expect(promise:getStatus()).to.equal(Promise.Status.Resolved)
expect(promise._values[1]).to.equal(2)
expect(promises[1]:getStatus()).to.equal(Promise.Status.Cancelled)
expect(promises[2]:getStatus()).to.equal(Promise.Status.Resolved)
end)
end)
end

9166
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

30
package.json Normal file
View file

@ -0,0 +1,30 @@
{
"name": "roblox-lua-promise",
"version": "0.0.0",
"description": "An implementation of `Promise` similar to Promise/A+.",
"main": "-",
"directories": {
"lib": "lib"
},
"dependencies": {
"gh-pages": "^2.1.1",
"vuepress": "^1.0.3",
"vuepress-plugin-api-docs-generator": "^1.0.12"
},
"devDependencies": {},
"scripts": {
"docs:dev": "vuepress dev .",
"docs:build": "vuepress build .",
"docs:publish": "gh-pages -d ./.vuepress/dist"
},
"repository": {
"type": "git",
"url": "git+https://github.com/evaera/roblox-lua-promise.git"
},
"author": "",
"license": "MIT",
"bugs": {
"url": "https://github.com/evaera/roblox-lua-promise/issues"
},
"homepage": "https://github.com/evaera/roblox-lua-promise#readme"
}

View file

@ -1,10 +0,0 @@
{
"name": "lua-promise",
"servePort": 8000,
"partitions": {
"lib": {
"path": "lib",
"target": "ReplicatedStorage.Promise"
}
}
}