GO style control flow in Javascript with Yieldable actions.
gojy is redux style middleware that treats generators as sequential blocking threads. These threads will block on yielded promises and generator - very much like co. gojy however, uses a different concurrency mechanism. Whereas co utilizes arrays and objects, gojy uses the go action. When a go action is yielded a promise is returned that resolves when the go routine completes. This promise can then be yielded at a later point in time to wait for the result.
gojy's concurrency mechanism provides three advantages over co:
- it's more powerful
- it doesn't overload objects and arrays so that they can be used as actions
- it pools goroutines run by an instance of a runner, so that they can all be killed
$ npm install gojy
const {run, go, join} = require('gojy')
run(function * () {
// launch go routine without blocking
const promise1 = yield go(function * () {
yield fetch('google.com')
yield fetch('facebook.com')
})
// launch go routine without blocking
const promise2 = yield go(function * () {
yield fetch('segment.io')
yield fetch('mixpanel.io')
})
// block
yield join([promise1, promise2])
})
A pure runner with no additional action processing.
process
- generator to run
Returns: result of generator
Creates a runner with additional action processing handled by middleware
.
middleware
- redux style middleware
Returns: a gojy runner
Returns: the gojy middleware for use in redux middleware stacks
Launch a goroutine
goroutine
- goroutine to run
Returns: a promise that resolves on goroutine completion
Kill running goroutines launched by runner.
Helpers for managing control flow.
Turn collection to a promise and block on it.
collection
- the promise or collection of promises to block on
Returns: result of promise
implementation:
function * join (collection) {
return yield toPromise(collection)
}
Async sequential for each.
generator
- async iterateecollection
- collection to iterate over
Async sequential map.
generator
- async iterateecollection
- collection to iterate over
Returns: mapped collection
Run collection in parallel and block. Gives you similar behavior to co yielded arrays and objects.
collection
- the collection of goroutines to run in parallel
Returns result of collection goroutines
implementation:
function * now (collection) {
return yield join(yield map(go, collection))
}
Some handy dandy goisms.
Sleep for time.
Simple promise based channel implementation.
Returns: take and put functions for the created channel
Go inspired error handling by matthewmueller
Returns: error first array ([err, ...])
Wait on multiple promises and selects first.
cases
- array of cases to wait on. Each case is a tuple of the form [promise, cb].
Returns: result cb of fasest promise
Example:
const res = yield select([
[fetch('google'), _ => 'google is better'],
[fetch('facebook'), _ => 'facebook is better']
])
console.log(res) // => `google is better`
MIT