Each
This Plug-in is used to apply an asynchronous function to each element in a specified array. The function should return immediately and accept a callback function as its final argument.
prop eachrequired
The each property defines an object with properties that control how the state should use the plug-in.
prop each.fnrequired
The each.fn property is used to defined the asynchronous function used by the plug-in. This property has one of the following syntaxes:
- A string that names an asynchronous function (contained within the
importsobject) - A variable that holds a reference to an asynchronous function
- An inline function definition defining the asynchronous function
Using the string syntax helps to create better diagrams for very little overhead and is therefore recommended.
prop each.fnArgsoptional
A synchronous function used to produce the arguments that are passed to the asynchronous function. The each.fnArgs function is called for each element of the array and is passed the current item from the array and its index. The function should return either a single argument or an array of arguments.
If the parameter is undefined then the asynchronous function argument used for each element of the array is simply that element.
prop each.iteratoroptional
A synchronous function that is called each time the asynchronous functions callback is called (indicating its completion). The first argument is an index (based on start order), followed by the same arguments as those in the callback for the asynchronous function. The return value of this function is ignored.
prop each.overoptional
The each.over property sets the array which will be iterated over. This property has one of the following syntaxes:
- An array
- A synchronous function returning an array
undefined, in which case the first argument from the transition arguments (which should be an array) is used
prop each.paroptional
The each.par parameter sets the maximum number of array elements used in parallel at any one time. This allows anything from purely sequential processing (i.e. each.par = 1) to complete parallel processing (i.e. each.par = size of the array) to be supported.
If the parameter is undefined then a default value of 4 is used.
event 'each.done'
An event called 'each.done' is generated and injected into the current state when when all the array elements have been used and all the respective asnychronous functions calls have returned.
Example
The following example uses the each plug-in to iterate through an array or URLs (taken from the first argument of the transition arguments), load them using the request module and dump the contents to the console.
PageDump: {
each: {
fn: 'request',
fnArgs: function (item, index) {
return { uri: item };
},
iterator: function (index, err, response, body) {
if (err) {
console.error(index, err);
} else {
console.log(index, body);
}
}
},
actions: {
'each.done': '@exit'
}
}
See
- source: each.js
- example: weather_forecast.js