thunk is a function that encapsulates synchronous or asynchronous code inside.
thunk accepts only one callback function as an arguments, which is a CPS function.
thunk returns another thunk function after being called, for chaining operations.
thunk passes the results into a callback function after being excuted.
If the return value of callback is a thunk function, then it will be executed first and its result will be sent to another thunk for excution, or it will be sent to another new thunk function as the value of the computation.
Matrix of thunk, it generates a thunkFunction factory (named thunk) with it's scope.
"scope" refers to the running evironments thunk generated(directly or indirectly) for all child thunk functions.
Here's how you create a basic thunk, any exceptions would be passed the next child thunk function:
const thunk = thunks()
Here's the way to create a thunk listening to all exceptions in current scope with onerror, and it will make sure the exceptions are not being passed to the followed child thunk function, unless onerror function returns true.
Create a thunk with onerror, onstop and debug listeners. Results of this thunk would be passed to debug function first before passing to the followed child thunk function.
const thunk = thunks({ onstop: function (sig) { console.log(sig) }, onerror: function (error) { console.error(error) }, debug: function () { console.log.apply(console, arguments) }})
Equals:
const scope = new thunks.Scope({ onstop: function (sig) { console.log(sig) }, onerror: function (error) { console.error(error) }, debug: function () { console.log.apply(console, arguments) }})const thunk = thunks(scope)
The context of onerror, onstop and debug is a scope.
Even multiple thunk main functions with different scopes are composed,
each scope would be separate from each other,
which means, onerror, onstop and debug would not run in other scopes.
thunks.pruneErrorStack
Default to true, means it will prune error stack message.
thunks.onerror(error)
Default to null, it is a global error handler.
Class thunks.Scope
const scope = new thunks.Scope({ onstop: function (sig) { assert.strictEqual(this, scope) }, onerror: function (error) { assert.strictEqual(this, scope) }, debug: function () { assert.strictEqual(this, scope) }})const thunk = thunks(scope)
thunk(thunkable)
This is the thunkFunction factory, to create new thunkFunction functions.
The parameter thunkable value could be:
a thunkFunction function, by calling this function a new thunkFunction function will be returned
obj can be an array or an object that contains any value. thunk.all will transform value to a child thunk function and excute it in parallel. After all of them are finished, an array containing results(in its original order) would be passed to the a new child thunk function.
thunkX can be any value, thunk.seq will transform value to a child thunk function and excute it in order. After all of them are finished, an array containing results(in its original order) would be passed to the a new child thunk function.
thunk.seq([ function (callback) { setTimeout(function () { callback(null, 'a', 'b') }, 100) }, thunk(function (callback) { callback(null, 'c') }), [thunk('d'), function * () { return yield 'e' }], // thunk in array will be excuted in parallel function (callback) { should(flag).be.eql([true, true]) flag[2] = true callback(null, 'f') }])(function (error, value) { console.log(error, value) // null [['a', 'b'], 'c', ['d', 'e'], 'f']})
or
thunk.seq( function (callback) { setTimeout(function () { callback(null, 'a', 'b') }, 100) }, thunk(function (callback) { callback(null, 'c') }), [thunk('d'), thunk('e')], // thunk in array will be excuted in parallel function (callback) { should(flag).be.eql([true, true]) flag[2] = true callback(null, 'f') })(function (error, value) { console.log(error, value) // null [['a', 'b'], 'c', ['d', 'e'], 'f']})
Returns a child thunk function with the value or error from one first completed.
thunk.thunkify(fn)
Returns a new function that would return a child thunk function
Transform a fn function which is in Node.js style into a new function.
This new function does not accept a callback as an argument, but accepts child thunk functions.
lift comes from Haskell, it transforms a synchronous function fn into a new async function.
This new function will accept thunkable arguments, evaluate them, then run as the original function fn. The new function returns a child thunk function.
const thunk = require('thunks')()function calculator (a, b, c) { return (a + b + c) * 10}const calculatorT = thunk.lift(calculator)let value1 = thunk(2)let value2 = Promise.resolve(3)calculatorT(value1, value2, 5)(function (error, result) { console.log(result) // 100})
it transforms thunkable value to a persist thunk function, which can be called more than once with the same result(like a promise). The new function returns a child thunk function.
This will stop control flow process with a message similar to Promise's cancelable(not implemented yet). It will throw a stop signal object.
Stop signal is an object with a message and status === 19(POSIX signal SIGSTOP) and a special code. Stop signal can be caught by onstop, and aslo can be caught by try catch, in this case it will not trigger onstop.
const thunk = require('thunks')({ onstop: function (res) { if (res) console.log(res.code, res.status, res) // SIGSTOP 19 { message: 'Stop now!' } }})thunk(function (callback) { thunk.stop('Stop now!') console.log('It will not run!')})(function (error, value) { console.log('It will not run!', error)})
thunk.delay(100)(function () { console.log('Hello') return thunk.delay(100)(function () { thunk.stop('Stop now!') console.log('It will not run!') })})(function (error, value) { console.log('It will not run!')})
thunk.cancel()
This will cancel all control flow process in the current thunk's scope.
TypeScript Typings
import * as assert from 'assert'import { thunk, thunks, isGeneratorFn } from 'thunks'// or: import * as thunks from 'thunks'thunk(function * () { assert.strictEqual(yield thunks()(1), 1) assert.ok(isGeneratorFn(function * () {})) while (true) { yield function (done) { setTimeout(done, 1000) } console.log('Dang!') }})()
What functions are thunkable
thunks supports so many thunkable objects. There are three kind of functions:
thunk-like function function (callback) { callback(err, someValue) }
generator function function * () { yield something }
async/await function async function () { await somePromise }
thunks can't support common functions (non-thunk-like functions). thunks uses fn.length === 1 to recognize thunk-like functions.
Using a common function in this way will throw an error:
thunk(function () {})(function (err) { console.log(1, err) // 1 [Error: Not thunkable function: function () {}]})thunk(function (a, b) {})(function (err) { console.log(2, err) // 2 [Error: Not thunkable function: function (a, b) {}]})thunk(function () { let callback = arguments[0]; callback() })(function (err) { console.log(3, err) // 3 [Error: Not thunkable function: function () { let callback = arguments[0]; callback() }]})thunk()(function () { return function () {} // can't return a non-thunkable function.})(function (err) { console.log(4, err) // 4 [Error: Not thunkable function: function () {}]})
So pay attention to that. We can't return a non-thunkable function in thunk. If we return a thunkable function, thunk will evaluate it as an asynchronous task.