Repository navigation
API document
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, and give cb a value or an Error sync or async, to be passed to downstream when Action are fired.
var Action = require('action-js');
var fs = require('fs');
var readFileAction = new Action(
function(cb){
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, no matter it's a Error or not.
If the action function have return value, it will be returned immediately, check ajax below that we return the xhr object in this way.
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(Error still will 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 action function have return value, it will be returned immediately, check ajax below that we return the xhr object in this way.
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){
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 will 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 occured.
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
})Repeat action n times, pass the last action's value to downstream, if stopAtError is true, any Error will stop the repeating and 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.Try 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 thrown.
Try run action, if failed, retry action n times at most with delay milliseconds as interval, the action will be fired n + 1 times at most, if all failed, an Error 'RETRY_ERROR: Retry limit reached' will be thrown.
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()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.
Convert a node style(second 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);
});