Repository navigation
API document
function Action(go){
this._go = go;
}This is the constructor of Action which wrap an sync or async action inside, the go should be a function that wait for a cb, aka. a continuation, inside this continuation you should call cb with a value or an Error sync or async, single or multiply times, these values will be passed to downstream when Action are fired, sync or async, single or multiply times.
var Action = require('action-js');
var fs = require('fs');
var readFileAction = new Action(
function(cb){
return fs.readFile("data.txt", function(err, data){
if (err) {
cb(err);
}else{
cb(data);
}
});
}
);_go is the async action wrapped inside the Action, fire an Action immediately by passing a cb to it, it will not delayed to next tick, cb will receive the value produced by Action, sync or async, single or multiple times, no matter it's a Error or not.
If the continuation has a return value, it will be returned immediately, please check Return value of go.
readFileAction._go(function(data){
if (data instanceof Error){
console.log('Oh, no...');
}else{
console.log(data);
}
})Fire an Action with given cb, cb will receive the value produced by Action only if it's not an Error, otherwise the Error will be thrown, leave cb empty to ignore the value(but an Error will still be throw), the Error is thrown asynchronously, so you can't use normal catch to catch it, put a guard before go instead, see below.
If the continuation has a return value, it will be returned immediately, please check Return value of go.
Return an new Action with given cb added to the chain, cb will receive the value produced by original Action, no matter it's an Error or not, the return value of cb will be pass to downstream, you can return an Action inside cb to insert a new async action into the chain.
var processAction = readFileAction
._next(function(data){
if (data instanceof Error){
return 'error handled';
}else{
return processA(data);
}
})
._next(function(data){
return new Action(function(cb){
asyncProcessB(data, cb)
})
})
processAction.go(function(data){
console.log(data);
})Return an new Action with given cb added to the chain, cb will receive the value produced by original Action only if it's not an Error, the return value of cb will be pass to downstream, you can return an Action inside the cb to insert a new async action.
Return an new Action with given cb added to the chain, cb will receive the value produced by original Action only if it's an Error, and the return value of cb will be pass to downstream, you can return an Action inside the cb to insert a new async action.
Return a function that will run fn and return its result if no Error occured, otherwise return err.
var FuncMayReturnErr = Action.safe( (new Error 'Error: custom error'), FuncMayThrowErr);
FuncMayReturnErr(params);
// If FuncMayThrowErr(params) throw error, we return Error 'Error: custom error'Return a function that will run fn and return its result if no Error occured, otherwise return error.
Wrap a value in an Action.
Action.wrap('OK');
// it's equivalent to
new Action(function(cb){
return cb('OK');
});Fire action immediately(not next tick), memorize the resolved value, and return a new Action that will always give the same value without run the action again.
// The file will be read now, and saved in dataFrozen
var dataFrozen = Action.freeze(readFileAction.next(process))
dataFrozen.go(function(data){
console.log(data);
})
dataFrozen.go(function(data){
console.log(data);
})
// two console.log should always be the sameGiven an array of functions which product Action, run them in order, use the result of former Action to produce later Action, pass the value of the last Action to downstream, or pass Error if occurred.
The return value is not a new Action, but a function which product Action, pass an argument to it as the init value of the chain.
var accAction = function(x){
return new Action(function(cb){
cb(x+1);
});
}
Action.chain([accAction, accAction, accAction])(0)
.go(function(x){
console.log(x);
// should be 3
})Return an Action which will repeat action n times, pass the last action's value to downstream, if stopAtError is true, any Error will stop repeating and the error will be passed, repeat forever if n = -1.
Return an Action delay the action n milliseconds.
Action.repeat(-1,
Action.delay(1000, readFileAction)
.next(function(data){
console.log(data);
})
)
.go()
// now the file will be read every 1 second forever.Return an Action which will run action, if failed, retry action n times at most, the action will be fired n + 1 times at most, if all failed, an Error 'RETRY_ERROR: Retry limit reached' will be passed on, retry forever if n == -1.
Return an Action which will run action in actions array in parallel and collect results in an Array, if stopAtError is true, stop at Error and pass the error, otherwise save the error in the result array.
Action.parallel([ActionA, ActionB])
.go(function(datas){
console.log(datas[0]); // will be an Error if ActionA return an Error
console.log(datas[1]); // will be an Error if ActionB return an Error
})
Action.parallel([ActionA, ActionB], true)
.next(function(datas){
...
// if ActionA or ActionB return Error, this will be skipped
})
.guard(function(e){
...
})
.go()This is a lightweight version of parallel for running two Actions together, the cb will receive two results from action1 and action2, the results may be Errors, so guard them if you must.
Action.parallel(ActionA, ActionB, function(data0, data1){
console.log(datas0); // will be an Error if ActionA return an Error
console.log(datas1); // will be an Error if ActionB return an Error
})
.go()Run action in actions array in parallel and find the first result, if stopAtError is true, stop at Error and pass the error, otherwise continue to look for the first none Error value.
Run action in actions array in sequence and collect results in an Array, if stopAtError is true, stop at Error and pass the error, otherwise save the error in the result array.
Use generator function to chain action in a more imperative way, inside the generator function, you can wait an Action's value using yield:
var readFileAction = makeNodeAction(fs.readFile)
var actionFoo = Action.co(function*(paths){
var content = '';
var i = 0;
while(content.length < 1000)
content = yield readFileAction(paths[i++], {encoding: 'utf8'});
if (content !== ''){
console.log(content);
}
});
actionFoo(['./foo.txt', './bar.txt' ... ]).go();
// print the first file content >= 1000Since Action's semantic match perfectly with await, the underline implementation is much shorter:
spawn = function(gen, action, cb) {
return action._go(function(v) {
var done, nextAction, ref;
if (v instanceof Error) {
gen["throw"](v);
}
ref = gen.next(v), nextAction = ref.value, done = ref.done;
if (done) {
return cb(v);
} else {
return spawn(gen, nextAction, cb);
}
});
};
Action.co = function(genFn) {
return function() {
var gen = genFn.apply(this, arguments);
return new Action(function(cb) {
return spawn(gen, gen.next().value, cb);
});
};
};Action.co is just a fancy way to compose Actions, but Error handling will be somehow different, you must use try-catch to wrap everything throw/yield Error inside generator function, if you want to send value to downstream, wrap it using Action.wrap and yield the action, so if you want to use guard like any other Action, do it like this:
var actionFoo = Action.co(function*(){
try{
...
// something may throw Error
// or some Action may pass Error
} catch (err) {
// you can deal with the error here
// and return something useful using yield
// or just wrap the Error and pass to downstream
yield Action.wrap(err);
}
});
actionFoo()
.guard(function(err){
// handle err here
})
.next(...)
.go()Since generator can reuse its executing context, it's faster than splitting them into several functions and connect them with next, so use co if you don't need too much modularity, see Benchmark.
Convert a node style(last argument is a callback with type like (err, data) -> undefined) into a function return Action.
var readFileAction = Action.makeNodeAction(fs.readFile)
readFileAction('data.txt', {encoding: 'utf8'})
.go(function(data){
console.log(data);
});Convert an object to a query string, for adding param to url.
var param = Action.param({
uid: 1
, posts:[
'foo'
, 'bar'
]
, test:{
foo: 'bar'
}
})
//param == "uid=1&posts%5B0%5D=foo&posts%5B1%5D=bar&test%5Bfoo%5D=bar"
//decodeURIComponent(param) == "uid=1&posts[0]=foo&posts[1]=bar&test[foo]=bar"Make a JSON with Padding request, if failed, error 'REQUEST_ERROR: error when making jsonp request' will be passed on, opts format:
{
url :: String
// target url, add params if you wish to send data
, callback :: String
// this is the callback key in the param
// omit it with default 'callback'
}When jsonp Action fired with go, the script tag are returned(will be removed from DOM after request finish).
var script = Action.jsonp({
url: 'http://jsonplaceholder.typicode.com/posts?' + Action.param({
userId: 2
})
}).go(function(data) {
console.log(script);
return console.log(data);
});Since the data are already deserialized via the Padding part of JSON with Padding, the data should be a javascript value.
Make an AJAX request, opts format:
{
url :: String
// target url, when using method without request body
// eg. 'GET', 'DELETE'
// add params if you wish to send data
, method :: String
// 'GET' | 'POST' | 'DELETE' | 'PUT' ...
, data :: String | Object | FormData
// request payload, only use this when request method support body
// String will add header: 'Content-Type', 'application/x-www-form-urlencoded'
// FormData will add header: 'Content-Type', 'multipart/form-data; boundary=...'
// Other Object will add header: 'Content-Type', 'application/json; charset=UTF-8'
, headers :: Object
// custom headers key-value pairs
, timeout :: Int
// max request time in milliseconds
, responseType :: String
// Enumerated value that defines the response type
// only works with some broswers
// check https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
}Without setting responseType, response are passed as string as it is, so deserialize it if you must, If request failed, error 'REQUEST_ERROR: statusx' will be passed on, x is the xhr status, if request didn't finish within given timeout, error 'REQUEST_ERROR: timeout' will be passed on. When ajax Action are fired, the xhr object will be returned without block.
// send data with urlencoded string
var xhr = Action.ajax({
method: 'POST',
url: 'http://jsonplaceholder.typicode.com/posts',
data: Action.param({
what: 3
})
})
.next(JSON.parse) // all responses are string if no responseType provided
.go(function(data) {
// use xhr object to obtain response headers
console.log(xhr.getAllResponseHeaders());
console.log(data);
});
// send object with json
var xhr = Action.ajax({
method: 'POST',
url: 'http://jsonplaceholder.typicode.com/posts',
data: {
foo: 'bar'
},
timeout: 100
}).guard(function(e) {
console.log(e);
return 'error handled';
}).go(function(data) {
console.log(data);
});
// send FormData
var f = new FormData();
var f.append('username', 'Chris');
var xhr = Action.ajax({
method: 'POST',
url: 'http://jsonplaceholder.typicode.com/posts',
data: f,
// use responseType to auto deserialize data
responseType: 'json'
}).go(function(data) {
console.log(data);
});