JSFiddle - React, Tailwind, and code Playground
JavaScript
// ================================================================
// async.waterfall([f1, f2, f3,...], cb(err, results))
// Runs the tasks array of functions in series, each passing their
// results to the next in the array. However, if any of the tasks
// pass an error to their own callback, the next function is not
// executed, and the main callback is immediately called with the
// error.
// ================================================================
// JSFiddle helpers
var process = {nextTick:function(fn){ setTimeout(fn); }};
document.body.innerHTML = "";
var log = function(str){
document.body.innerHTML += str + "<br />";
};
// Recursive function, where `tasks` corresponds to the functions left
// to process, `cb` corresponds to waterfall's final callback, and any
// additional arguments are data passed to the next function in tasks.
function waterfall(tasks, cb /*, arg1, arg2 ... */) {
cb = cb || function() {};
// support for arbitrary # of arguments passed along by functions
var data = Array.prototype.slice.call(arguments, 2);
if (!Array.isArray(tasks)) return cb('tasks must be an array');
// check if there are functions left
if (!tasks[0]) {
// avoid race condition with
if (data.length > 1) cb(null, data);
else cb(null, data[0]);
return;
}
// process the next function
var next = tasks[0];
data.push(function(err) {
if (err) return cb(err);
// build the args for waterfall...
var args = [];
// remaining functions
args.push(tasks.slice(1));
// final waterfall callback
args.push(cb);
// arbitrary # of args for next function
args.push.apply(args, Array.prototype.slice.call(arguments, 1));
process.nextTick(function() {
waterfall.apply(null, args);
});
});
next.apply(null, data);
};
// TEST
function f1(cb) {
var running_sum = 1;
running_sum += 1;
cb(null, running_sum);
};
function f2(running_sum, cb) {
running_sum += 2;
cb(null,...