-
Notifications
You must be signed in to change notification settings - Fork 51
Futures
If you omit the callback (or pass a null callback) when calling a streamline function, the function will execute synchronously and return a 'future'. The future is just a function that you can call later to obtain a result. Let us see how it works on an example:
function countLines(path, _) {
return fs.readFile(path, _).split('\n').length;
}
function compareLineCounts(path1, path2, _) {
// parallelize the two countLines operations
var n1 = countLines(path1);
var n2 = countLines(path2);
// join the results
return n1(_) - n2(_);
}
Streamline does not really provide any special API to manipulate 'futures' (and it does not provide any 'promise' abstraction either). The 'future' which is returned is a simple function with a simple parameter, which is a node-style callback (function(err, result) { ... }).
You can use futures to parallelize operations on an array. For example, the following function will compute the number of lines for an array of path names:
function lineCounts(paths, _) {
// start all the operations in parallel
var futures = paths.map(function(path) {
return countLines(path1);
});
// collect the results into an array
return flows.map(_, futures, function(_, future) {
return future(_);
});
}
Of course, if you call lineCounts without any callback, it will return a future which resolves into an array of line counts. So you can call the previous function either as:
// classical way: pseudo-synchronous
var counts = lineCounts(paths, _);
or as:
// get a future
var countsF = lineCounts(paths);
// do other things while lineCounts is running
doSomethingElse(_);
// get the future's value
var counts = countsF(_);