Righto
Simple, Fast, Cross-API eventuals.
An Eventuals implementation that:
- Lets you use synchronous functions, err-backs (normal callback style), promises, iterators (yield), whatever you like.
- Are lazily evaluated.
- Implicitly (and transparently) handles execution order and parallelisation.
- Provides a solution for all common (and some less common) async flows, parallel, waterfall, series, etc, etc...
- Doesn't catch thrown errors. Why is this good?
righto
takes a task to run, and arguments to pass to the task. If you pass any eventual arguments (rightos or promises), they will be resolved before running the dependant task.
righto
'd tasks are resolved once and the result is cached. If a task is in flight when it's results are asked for, the results will be passed when the task resolves.
QUICK REFERENCE
Signature:
righto(cps-function, ...args) -> fn(err-back)
where:
a cps-function has signature: cps-function(...args, err-back) -> void
an err-back has signature: err-back(error, ...results) -> void
Examples
Simple Example: read some files
var fs = ; { ;}; var myFile = ;var mySecondFile = ;var concattedFiles = ; ;
A more involved example: return a document for a user while checking permissions.
// Make a task from an err-back functionvar document = ; var user = ; // Resolve an object with eventual properties to pass to a function.var account = ; // Reject the flow if a business rule is not met{ ifdocumentownerId !== accountid return righto; } // Make a task from a synchronous function// Depend on `document` and `account` in parallel, automatically.var hasPermission = righto; // Take results from a task only after another task is completevar allowedDocument = righto; // Use the results.;
Who's using it?
Used in the backend of https://7tennis.com.au/, which handled 800k concurrent users for the early 2017 season.
The inventor of JavaScript said it was cool in a tweet once: https://twitter.com/BrendanEich/status/1059210746163130368
Usage:
var eventual = ;
API support
Callbacks
righto suports passing error-first CPS functions by default as tasks:
{ ;} var eventuallyFoo = ; ;
Promise
righto supports passing Promises as a dependency:
var somePromise = { ;}; var someRighto = ; ;
And supports easily integrating back to promises:
var someRighto = ; var somePromise = righto; somePromise;
Warning:
- promises execute immediately.
- promises will catch any errors thrown within their resolver, and turn them into rejections.
Righto can't help you once you pass control back to promises :)
Generators (yield)
righto supports running a generator (or any next
able iterator):
var generated = righto; var result = ; ;
Errors
Errors bubble up through tasks, so if a dependency errors, the task errors.
// Task that errors{ ; } var getFoo = ; { ;} var getBar = ; ;
Immediately execute
You can force a righto task for run at any time without dealing with the results (or error) by calling it with no arguments:
// Lazily resolve (won't run untill called)var something = ; // Force something to start resolving *now*; // later ... ;
Also, since righto tasks return themselves when called, you can do this a little more shorthand, like so:
// Immediately force the righto to begin resolving.var something = ; // <= note the call with no arguments. // later ... ;
Take / Multiple results
By default, dependent tasks are passed only the first result of a dependency righto
. eg:
{ ;} var getFoo = ; { ;} var getBar = ; ;
But you can pick and choose what results are used from a dependency like so:
// foo() and bar() as defined above... var getBar = ; // Take result 0, and result 2, from getFoo ;
Reduce
righto.reduce takes an Array of values (an an eventual that resolves to an array) as the first argument, resolves them from left-to-right, optionally passing the result of the last, and the next task to a reducer.
If no reducer is passed, the tasks will be resolved in series, and the final tasks result will be passed as the result from reduce.
If a reducer is used, a seed can optionally be passed as the third parameter.
If no tasks are passed, the final result will be undefined
.
No reducer passed:
{ aCalled = true; t; ;} { t; ;} var result = righto; ;
With a custom reducer, and seed.
{ aCalled = true; t; ;} { t; ;} // Passes previous eventual result to next reducer call.var result = righto; ;
After
Sometimes you need a task to run after another has succeeded, but you don't need its results, righto.after(task1, task2, taskN...) can be used to achieve this:
{ ;} var getFoo = ; { ;} var getBar = ; // wait for foo before running bar. ;
All
righto.all takes N tasks, or an Array of tasks as the first argument, resolves them all in parallel, and results in an Array of results.
var task1 = ; var task2 = ; var task3 = ; var all = rightoalltask1 task2 task3; ;
Sync
Synchronous functions can be used to create righto tasks using righto.sync:
var someNumber =
Eventuals can also be returned from inside righto.sync, which will be resolved within the flow.
righto.sync(createARighto, args...); // Calls createARighto with args..., and then returns a new righto that resolves the result
righto.sync(createAPromise, args...); // Calls createAPromise with args..., and then returns a new righto that resolves the results
From
Anything can be converted to a righto with righto.from(anything);
righto; // Returns someRightorighto; // Returns a new righto that resolves the promiserighto; // Returns a new righto that resolves 5
Value (passing resolvables as unresolved arguments)
Sometimes it may be required to pass a resolvable (a righto, or promise) as an argument
rather than passing the resolved value of the resolvable. you can do this using righto.value(resolvable)
var righto1 = ; var rightoValue = rightovaluerighto1; var righto2 = ; ;
Get
You can create a new righto
that resolves the key/runs a function on a result like so:
var user = ; var userName = user;// OR: Use a functionvar userName = user; ;
And keys can be righto
's as well:
var user = ;var userKey = ; var userName = user; ;
Surely
You can resolve a task to an array containing either
the error or results from a righto with righto.surely
,
which resolves to an array in the form of [error?, results...?]
.
var errorOrX = righto; var errorOrY = righto; var z = ; ;
Handle
Wrap a righto task with a handler that either forwards the successful result, or sends the rejected error through a handler to resolve the task.
{ ifMath > 05 ; else ; }; { ;} var maybeAString = aString = righto; ;
This can also be used to pass custom error results:
{ iferrorcode === 'ENOENT' return ; return ;} var aFile = aFileOrNull = righto; ;
Resolve
Resolves an object to a new object where any righto values are resolved:
var foo = ; // recursively resolve child objects// Vvar bar = righto; ;
Mate
Occasionally you might want to mate a number of tasks into one task.
For this, you can use righto.mate.
{ // eventually... ;} var stuff = ; { // eventually... ;} var otherStuff = ; var stuffAndOtherStuff = righto; ;
Fail
A shorthand way to provide a failed result.
This is handy for rejecting in .get methods.
var something = someRighto;
Proxy support
If you are using righto in an environment that supports proxies, you can use the proxy API:
var righto = proxy; var foo = ; foo;
The proxied api always returns the proxied version, meaning you can dot-access arbitrarily:
var righto = proxy; var foo = ; foobar;
isRighto, isThenable, isResolvable
Use these methods to check if something is a righto, a thenable, or resolvable (either righto or thenable);
var rigthoA = ; var promiseB = { ;}; righto; -> truerighto; -> falserighto; -> falserighto; -> truerighto; -> truerighto; -> true
Tracing
You can get a trace of where a righto went to resolve its dependencies by setting:
righto_debug = true;
which will tell any following calls to righto
to store a stack trace against it.
You can then retrieve the trace with:
var x = ; x; ->
something (.../index.js:1034:13)
- argument "b" from taskB (.../index.js:1022:13)
- argument "a" from taskA (.../index.js:1016:13)
- argument "c" from taskC (.../index.js:1028:13)
- argument "a" from taskA (.../index.js:1016:13)
- argument "b" from taskB (.../index.js:1022:13)
- argument "a" from taskA (.../index.js:1016:13)
You can also tell righto to print a graph trace, highlighting the offending task, when a graph rejects.
Either per-righto:
var task = ; task_traceOnError = true; ;// Logs...
Or globally:
righto_autotraceOnError = true;
Which print handy traces like this one:
NOTE:
Only rightos that were instantiated after setting the debug flag will support tracing.
Unsupported from v1.
The take/ignore syntax that used a single righto within an array has been deprecated due to it having been a bad idea that I should never have implemented to begin with.
This syntax was deprecated a few v1 versions ago, so you can get a console.warn for potential usages of the syntax by turning on _debug mode and _warnOnUnsupported:
righto_debug = true;righto_warnOnUnsupported = true; // ... code ... var getFoo = ; // <- the unsupported syntax ; // -> console.warn()'s the line number where it was used.