-
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 single function seq()
.
var f = seq(f1, ... , fN);
var promise = f(init);
or
var f = seq([f1, ..., fN], Deferred);
var promise = f(init);
The first version assumes that internally the standard Promise
is used. The second version takes an array, and an optional Deferred
argument to specify what to use internally (usually async.Deferred or async.FastDeferred). To make working with it simple, it is added to extended modules async.Deferred-ext and async.FastDeferred-ext.
Conceptually seq()
takes an array of asynchronous or regular functions (asynchronous functions are functions that return promises). Those functions takes one argument, and return a value (usually a promise). They are chained as described above and an initialization function is returned, which takes a single argument: an initial value to start the sequence, and returns a promise.
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 seq = require('heya-async/seq');
var chain = seq(
function (value) { return value + 1; },
function (value) { return 2 * value; },
function (value) { return value / 10; }
);
chain(24).then(function (value) {
console.log('Should be 5:', value);
return value;
});
chain(14).then(function (value) {
console.log('Should be 3:', value);
return value;
});