-
Notifications
You must be signed in to change notification settings - Fork 1
async.seq
This module provides a helper to run asynchronous operations sequentially waiting for previous one to finish, and passing a result from one function to another. Conceptually it is like connecting functions using a then()
chain:
var result = f1(initial).
then(function (value) { return f2(value); }).
then(function (value) { return f3(value); }).
then(function (value) { return f4(value); }).
then(function (value) { return f5(value); });
The module returns a function, which takes one argument: an optional deferred constructor (realistically Deferred or FastDeferred) to be used to construct internal promises. If that argument is falsy, or missing, the standard Promise
will be used. Module seq provides this algorithm instrumented with Promise
.
As a result, a single function is returned, which takes an array of functions. Those functions are chained as described above and an object is returned with following properties:
-
resolve()
— a function, which starts the whole chain, by calling the very first function with its argument. -
reject()
— a function, which fails the whole chain. -
progress()
— a function, or a falsy value, to pass through progress values, if an underlying promise supports them. -
begin
— a promise that starts the chain. -
end
— a promise at the end of the chain. It is used to add more processing after the chain has finished executing.
Note: function in the initial array can return promises or any other values, but the whole value of chaining is in handling asynchronous functions returning promises.
Simple example with synchronous functions:
var Deferred = require('heya-async/Deferred');
var genSeq = require('heya-async/generic/seq');
var seq = genSeq(Deferred);
var chain = seq([
function (value) { return value + 1; },
function (value) { return 2 * value; },
function (value) { return value / 10; }
]);
chain.end.then(
function (value) { console.log('Should be 5:', value); return value; });
chain.resolve(24); // start the chain